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

把字符串转换成整数

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;
        }
    }
}
全部评论

相关推荐

人生一梦:24年我投暑期实习,它以我不是女的为理由拒绝了我查看图片
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务