题解 | #把字符串转换成整数(atoi)#

把字符串转换成整数(atoi)

https://www.nowcoder.com/practice/d11471c3bf2d40f38b66bb12785df47f

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 *
 * @param s string字符串
 * @return int整型
 */
      function StrToInt(s) {
    // write code here
    let res = [];
    let str = s.trim();
    let hx=''
    if (s === "-" || (s === "" || s === " ")|| s==='+') {
        return 0;
    }
    if((str[0]==='-'&&str[1]==='+')|| (str[0]==='+'&&str[1]==='-')){
        return 0
    }
    if(Number(str)>=2147483647){
        return 2147483647
    }
      if(Number(str)<=-2147483648){
        return -2147483648
    }
    for (let i in str) {
      
        if (str[0] === "-") {
            str=str.slice(1);
            hx='-'
        }
        if( str[0]==='+'){
            str=str.slice(1);
        }

        if (str[0] > "9" || str[0] < "0") {
            return 0;
        }
        if((str[i] >='a'&& str[i] <='z') || str[i]==='-' || str[i]==='.' ||str[i]==='+'){
            // console.log("走啦吗")
                break
            }
        if (str[i] <= "9" && str[i] >= "0") {
            // console.log("====>",str[i])
             res.push(str[i]);
        }
    
    }
    // console.log(res)
    if (hx === "-") {
        return Number(hx + res.join(""));
    } else {
        return Number(res.join(""));
    }
}
module.exports = {
    StrToInt: StrToInt,
};

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务