标签:
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.
"10" => 10
"-1" => -1
"123123123123123" => 2147483647
"1.0" => 1
1 public class Solution { 2 /** 3 * @param str: A string 4 * @return An integer 5 */ 6 public int atoi(String str) { 7 if (str == null || str.length() == 0) 8 return 0; 9 str = str.trim(); 10 if (str.length() == 1 && (str.equals("+") || str.equals("-") || str.equals(".") || str.equals("0"))) { 11 return 0; 12 } 13 14 boolean isPositive = true; 15 long current = 0; 16 17 for (int i = 0; i < str.length(); i++) { 18 if (i == 0 && str.charAt(i) == ‘+‘) { 19 continue; 20 } else if (i == 0 && str.charAt(i) == ‘-‘) { 21 isPositive = false; 22 } else if ((str.charAt(i) == ‘.‘ && i == str.length() - 1) 23 || (str.charAt(i) == ‘.‘ && i == str.length() - 2 && str.charAt(str.length() - 1) == ‘0‘)) { 24 break; 25 } else if (str.charAt(i) >= ‘0‘ && str.charAt(i) <= ‘9‘) { 26 current = current * 10 + str.charAt(i) - ‘0‘; 27 if (isPositive && current > Integer.MAX_VALUE) 28 return Integer.MAX_VALUE; 29 if (!isPositive && -current < Integer.MIN_VALUE) 30 return Integer.MIN_VALUE; 31 } else { 32 break; 33 } 34 } 35 36 if (!isPositive) { 37 current = -current; 38 } 39 40 return (int) current; 41 } 42 }
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5697755.html