8. String to Integer (atoi)

ascii to integer的实现。判断的方法是进位累加。要格外注意'1'和1这样的char和int的区别。

  • 有效字符后面的省略。 The string can contain additional characters [after those] that form the integral number, which are ignored and have no effect on the behavior of this function.
  • 首次出现的sequence不是有效数字,返回0。
  • str为空或者全是空格,返回0。
  • outOfRange的时候返回INT_MIN/INT_MAX
    public int myAtoi(String str) {
        int total = 0, sign = 1, index = 0;

        if (str == null || str.length() == 0) return 0;

        //jump through spaces
        while (index < str.length() && str.charAt(index) == ' ') index++;

             //或者这么写:if(total > (Integer.MAX_VALUE - add) / 10) 
        if (str.charAt(index) == '+' || str.charAt(index) == '-') {
            sign = str.charAt(index) == '+' ? 1 : -1;
            index++;
        }

        //计算方法是进位累加
        while (index < str.length()) {
            //易错
            int digit = str.charAt(index) - '0';
            if (digit < 0 || digit > 9) break;
            if (total > Integer.MAX_VALUE / 10 || total == Integer.MAX_VALUE / 10 && digit > Integer.MAX_VALUE % 10) {
                total = sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
                break;
            }
            total = total * 10 + digit;
            index++;
        }
        return total * sign;
    }

注意INTMAX和INTMIN分别是2147483647和-2147483648,并不需要分开判断。很巧妙。

ref:
https://discuss.leetcode.com/topic/12473/java-solution-with-4-steps-explanations

你可能感兴趣的:(8. String to Integer (atoi))