【剑指offer】把字符串转换成整数

把字符串转换成整数

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

【思路】
处理空格-->首字符正负号-->循环计算时的非法字符-->int类型溢出

public class Solution {
    public int StrToInt(String str) {
        if (str == null || str.length() == 0) {
            return 0;
        }

        str = str.trim();
        if (str.length() == 0) {
            return 0;
        }

        boolean flag = false;
        long result = 0;
        char firstChar = str.charAt(0);
        if (firstChar == '+') {
            flag = false;
        } else if (firstChar == '-') {
            flag = true;
        } else if (firstChar >= '0' && firstChar <= '9') {
            result = firstChar - '0';
        }
        for (int i = 1; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (ch >= '0' && ch <= '9') {
                result *= 10;
                result += ch - '0';
            } else {
                return 0;
            }
        }
        if (flag) {
            result = -result;
        }
        if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
            return 0;
        }

        return (int) result;
    }

}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务