LeetCode 8 – String to Integer atoi

Posted on December 22, 2013

Last updated on December 22, 2013

Solution to LeetCode String to Integer atoi problem.

This is also an implementation question. The one interesting part is how to check for overflow/underflow.

public int atoi(String str) {
  char[] C = str.toCharArray();
  int N = C.length;
  int i = 0;
  int neg = 1;
  while(i < N && C[i] == ' ') i++; // we are at first nonspace char
  if(i == N) return 0; // out of characters

  if(C[i] == '+') i++;
  else if(C[i] == '-'){
    neg = -1;
    i++;
  }
  if(i == N) return 0; // out of chars

  if(C[i] < '0' && C[i] > '9') return 0; // wrong first character

  // C[i] is now the beginning of the number

  int result = 0;

  // Check for overflows and return the appropriate limit
  while(i < N && C[i] <= '9' && C[i] >= '0'){
    int digit = C[i] - '0';
    if(result > Integer.MAX_VALUE/10) return (neg > 0) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
    result = 10*result;
    if(result > Integer.MAX_VALUE-digit) return (neg > 0) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
    result += digit;
    i++;
  }

  return neg*result;
}
String to Integer atoi
Markdown SHA1: 7bd749e21c20052a2d8fe96a893931b2436bf920