String to Integer
Implement function atoi
to convert a string to an integer.
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.
Example
"10" => 10
"-1" => -1
"123123123123123" => 2147483647
"1.0" => 1
1 public class Solution { 2 public int myAtoi(String str) { 3 if (str == null || str.length() == 0) 4 return 0; 5 str = str.trim(); 6 if (str.length() == 1 && (str.equals("+") || str.equals("-") || str.equals(".") || str.equals("0"))) { 7 return 0; 8 } 9 10 boolean isPositive = true; 11 long current = 0; 12 13 for (int i = 0; i < str.length(); i++) { 14 if (i == 0 && str.charAt(i) == '+') { 15 continue; 16 } else if (i == 0 && str.charAt(i) == '-') { 17 isPositive = false; 18 } else if (str.charAt(i) >= '0' && str.charAt(i) <= '9') { 19 current = current * 10 + str.charAt(i) - '0'; 20 if (isPositive && current > Integer.MAX_VALUE) 21 return Integer.MAX_VALUE; 22 if (!isPositive && -current < Integer.MIN_VALUE) 23 return Integer.MIN_VALUE; 24 } else { 25 break; 26 } 27 } 28 29 if (!isPositive) { 30 current = -current; 31 } 32 33 return (int) current; 34 } 35 }