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.
spoilers alert... click to show requirements for atoi.
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
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.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
Solution:
1 public class Solution { 2 public int atoi(String str) { 3 str = str.trim(); 4 int length = str.length(); 5 if (length == 0) 6 return 0; 7 boolean minus = false; 8 int i = 0; 9 if (str.charAt(0) == '-') { 10 minus = true; 11 i++; 12 } else if (str.charAt(0) == '+') { 13 i++; 14 } 15 long num = 0l; 16 long max = Integer.MAX_VALUE; 17 long min = Integer.MIN_VALUE; 18 for (; i < length; ++i) { 19 char c = str.charAt(i); 20 if (c >= '0' && c <= '9') { 21 num *= 10; 22 num += c - '0'; 23 } else { 24 break; 25 } 26 if (minus && 0 - num < min) { 27 return Integer.MIN_VALUE; 28 } else if (!minus && num > max) 29 return Integer.MAX_VALUE; 30 } 31 32 return minus ? new Long(0 - num).intValue() : new Long(num).intValue(); 33 } 34 }