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

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

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

正则秒解

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param s string字符串 
 * @return int整型
 */
function StrToInt( s ) {
    // write code here
    let tmp=s.trim()
    let min=0-2**31
    let reg=/^[+-]*\d+/g
    let ans=tmp.match(reg)
    if(!ans) return 0     
    console.log(ans[0])
    if(ans[0].match(/[+-\s]{2}/)) return 0;
    if(ans[0]>2**31-1) return 2147483647; 
    if(ans[0]<min) return -2147483648;
               
    return ans[0]
    

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

相关推荐

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