Categories
interview

String to Integer (atoi) – Java

class Solution {
 public int myAtoi(String str) {
  int ret = 0;
  int i = 0;
  boolean negative = false;
  String retString = "";
  // Without using trim()
  // while(i<str.length() && str.charAt(i) == ' ')
  //     i++;
  str = str.trim();
  if (i >= str.length() || Character.isLetter(str.charAt(i)))
   return ret;
  if (str.charAt(i) == '-') {
   negative = true;
   i++;
  } else if (str.charAt(i) == '+') {
   i++;
  }
  while (i < str.length() && Character.isDigit(str.charAt(i))) {
   retString += str.charAt(i++);
  }
  if (retString != "") {
   try {
    ret = (negative ? -1 * Integer.parseInt(retString) : Integer.parseInt(retString));
   } catch (Exception e) {
    ret = (negative ? Integer.MIN_VALUE : Integer.MAX_VALUE);
   }
  }
  return ret;
 }
}