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

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

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

import java.util.*;


class Solution {
    public boolean isNumChar(char ch) {
        return ch >= '0' && ch <= '9';
    }
    public int StrToInt(String str) {
        int le = 0;
        while(le < str.length() && str.charAt(le) == ' ') {
            le++;
        }
        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(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;
        }
    }
}
全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务