LeetCode - 8. String to Integer

2016-03-15  本文已影响0人  Sinexs

Question


Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

这题的难点应该是atoi这个到底是个神马函数,输入输出的结果是啥。

查了查资料,发现是这样的规律:

貌似暂时就这么多。

所以应对这些规律的解题思路:

注意点:

Solutions


public class Solution {
    public int myAtoi(String str) {
        // 判断是否为空和长度是否为0
        if(str == null || str.length() == 0)
            return 0;
        
        // 去掉字符串首尾的空格
        str = str.trim();
        
        int sign = 1, start = 0, len = str.length();
        long sum = 0;
        
        // 判断符号
        char firstChar = str.charAt(0);
        if (firstChar == '+') {
            sign = 1;
            start++;
        } else if (firstChar == '-') {
            sign = -1;
            start++;
        }
        
        for (int i = start; i < len; i++) {
            if (!Character.isDigit(str.charAt(i))) // 判断是否为数字
                return (int) sum * sign;
                
            sum  = sum * 10 + str.charAt(i) - '0';
            
            // 判断是否越界
            if (sign == 1 && sum > Integer.MAX_VALUE) {
                return Integer.MAX_VALUE;
            }
            if (sign == -1 && (-1) * sum < Integer.MIN_VALUE) {
                return Integer.MIN_VALUE;
            }
        }
        
        return (int) sum * sign;
    }
}

Points


TO DO


暂无

上一篇下一篇

猜你喜欢

热点阅读