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.
The heart of this problem is dealing with overflow. A direct approach is to store the number as a string so we can evaluate at each step if the number had indeed overflowed. There are some other ways to detect overflow that requires knowledge about how a specific programming language or operating system works.
A desirable solution does not require any assumption on how the language works. In each step we are appending a digit to the number by doing a multiplication and addition. If the current number is greater than 214748364, we know it is going to overflow. On the other hand, if the current number is equal to 214748364, we know that it will overflow only when the current digit is greater than or equal to 8. Remember to also consider edge case for the smallest number, –2147483648 (–231).
1 private static final int maxDiv10 = Integer.MAX_VALUE/10; 2 public int myAtoi(String str) { 3 String s = str.trim(); 4 int i = 0, sign = 1; 5 if(i < s.length() && s.charAt(0) == '+') { 6 sign = 1; 7 i++; 8 } else if(i < s.length() && s.charAt(0) == '-'){ 9 sign = -1;10 i++;11 }12 int num = 0;13 while(i < s.length() && Character.isDigit(s.charAt(i))){14 int digit = Character.getNumericValue(s.charAt(i));15 if(num > maxDiv10 || num == maxDiv10 && digit >7){16 return sign == 1 ? Integer.MAX_VALUE:Integer.MIN_VALUE;17 }18 num = num * 10 + digit;19 i++;20 }21 return num * sign;22 }