题解 | 把字符串转换成整数(atoi)
把字符串转换成整数(atoi)
https://www.nowcoder.com/practice/d11471c3bf2d40f38b66bb12785df47f
/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return int整型 */ function StrToInt( s ) { // write code here let ans = s.trim(); let tag = ''; let isspecial = false; if (ans[0] == '-' || ans[0] == '+') { isspecial = true; if (ans[0] === '-') { tag='-' } else { tag=''; } } if (/[a-zA-Z]/.test(ans[0])) { return 0 } let res = "" for(let i = 0; i < ans.length; i++) { if (isspecial && i ==0) { continue; } if (/[\d]/.test(ans[i])) { res+=ans[i] continue; } if (/[\D]/.test(ans[i])) { // 非数字 break; } } console.log(res); let result = isNaN(parseInt(tag+res , 10)) ? 0 : parseInt(tag+res , 10); console.log(result) if (result > 2**31 -1) { result = 2**31 -1 } if (result < 0-2**31) { result = 0-2**31; } return result; } module.exports = { StrToInt : StrToInt };