Thinking process

Integer 立马应该想到

  • is it negative? positive? or 0
  • how to handle overflow?
  • no 0 or whitespace in the front

Mistakes

  • Convert to int not double, so there's no cases that the input has '.'
  • the input is valid, so there won't be any 0s at the front
  • Don't forget the white spaces that may appear in the front
  • Don't use for loop at the end
    • input: " -0012a"
    • should be -12
    • if using loop then it returns -130
public class Solution {
    private static final int maxDiv10 = Integer.MAX_VALUE / 10;

    public int myAtoi(String str) {
        int i = 0;
        int len = str.length();

        //white spaces
        while (i < len && Character.isWhitespace(str.charAt(i))) i++;

        //+ -
        int sign = 1;
        if (i < len && str.charAt(i) == '-') {
            sign = -1;
            i++;
        } else if (i < len && str.charAt(i) == '+') {
            i++;
        }

        int num = 0;
        //loop through the rest
        while (i < len && Character.isDigit(str.charAt(i))) {
            int digit = Character.getNumericValue(str.charAt(i));
            if (num > maxDiv10 || num == maxDiv10 && digit >= 8) {
                return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            }
            num = num * 10 + digit;
            i++;
        }

        return sign * num;
    }
}

results matching ""

    No results matching ""