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

把字符串转换成整数

http://www.nowcoder.com/practice/1277c681251b4372bdef344468e4f26e

function StrToInt(str)
{
    let numReg = /[0-9]/
    let sum = 0;
    let strMapNum = {
        '0':0,
        '1':1,
        '2':2,
        '3':3,
        '4':4,
        '5':5,
        '6':6,
        '7':7,
        '8':8,
        '9':9
    }
        for(let i = str.length - 1;i>=0;i--){
            let tmp = str[i]
            if(i==0){
                if(tmp === '-'){
                return 0 - sum
            }else if(tmp === '+'){
                  return sum  
            }     
            }

            if(!numReg.test(tmp)){
                return 0
            }
            let num = strMapNum[tmp] * Math.pow(10,str.length-i-1)
            sum += num
        }
    return sum


}
module.exports = {
    StrToInt : StrToInt
};
全部评论

相关推荐

故事和酒66:感觉够用了佬ps资格证书多了一行,最好精简成一面,hr看不了那么多字
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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