题解 | 把字符串转换成整数(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
};

全部评论

相关推荐

06-07 17:17
嘉兴学院 教师
单单人旁的佳:你是我见过最美的牛客女孩
点赞 评论 收藏
分享
Gaynes:查看图片
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务