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

把字符串转换成整数

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

public class Solution {
    public boolean isNumChar(char ch) {
        return ch >= '0' && ch <= '9';
    }
    public int StrToInt(String str) {
        int le = 0;
        if(le >= str.length()) {
            return 0;
        }
        char firstCh = str.charAt(le);
        boolean isNegative = false;
        if(firstCh == '+') {
            le++;
        } else if(firstCh == '-') {
            le++;
            isNegative = true;
        } else if(isNumChar(firstCh)) {

        } else {
            return 0;
        }
        int ri = le;
        while(ri < str.length() && isNumChar(str.charAt(ri))) {
            ri++;
        }
        if(ri != str.length()) {
            return 0;
        }
        if(isNegative) {
            long ans = 0;
            for(int i = le; i < ri; i++) {
                ans = ans * 10 - (str.charAt(i) - '0');
                if(ans < Integer.MIN_VALUE) {
                    return Integer.MIN_VALUE;
                }
            }
            return (int)ans;
        } else {
            long ans = 0;
            for(int i = le; i < ri; i++) {
                ans = ans * 10 + (str.charAt(i) - '0');
                if(ans > Integer.MAX_VALUE) {
                    return Integer.MAX_VALUE;
                }
            }
            return (int)ans;
        }
    }
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
昨天 17:10
什么素质,我请问呢,要掉小珍珠了。。。又憋屈又生气
Steven267:这不喷回去?花钱是大爷,记住这个道理
点赞 评论 收藏
分享
流浪的神仙:无恶意,算法一般好像都得9硕才能干算法太卷啦
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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