题解 | #把字符串转换成整数(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;
        }
    }
}
全部评论

相关推荐

05-19 15:21
已编辑
华南农业大学 Java
白火同学:你才沟通了200,说实话,北上广深杭这里面你连一座城市的互联网公司都没投满呢,更别说还有各种准一线二线城市了。等你沟通突破了三位数,还没结果再考虑转行的事吧。
点赞 评论 收藏
分享
Gaynes:查看图片
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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