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

把字符串转换成整数

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

比较简单的字符串转换

        if(str == null) return 0;
        if (str.charAt(0) >= 'a' && str.charAt(0) <= 'Z' ) return 0;
        boolean isNegative = str.charAt(0) == '-';
        int index = str.charAt(0) == '-' || str.charAt(0) == '+' ? 1 : 0;
        if (str.length()> 2 && str.charAt(1) == '0') index++;
        int res = 0;
        while (index < str.length() && str.charAt(index) >= '0' &&  str.charAt(index) <='9'){
            //核心部分就这一句,其他部分属于边边角角问题
            'res = res*10 + str.charAt(index)-'0';'
            index++;
        }
        if (index != str.length()) return 0;
        return isNegative ? -res : res;
    }
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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