8. 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.isEmpty()) return 0;
 4         int sign = 1, base = 0, i = 0;
 5         while (i < str.length() && str.charAt(i) == ' ') {
 6             i++;
 7         }
 8         if (i == str.length()) return 0;
 9         if (str.charAt(i) == '-' || str.charAt(i) == '+') {
10             sign = str.charAt(i) == '-' ? -1 : 1;
11             i++;
12         }
13         while (i < str.length() && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
14             if (base > Integer.MAX_VALUE / 10 || (base == Integer.MAX_VALUE / 10 && str.charAt(i) - '0' > 7)) {
15                 return (sign == 1) ? Integer.MAX_VALUE : Integer.MIN_VALUE;
16             }
17             base = 10 * base + (str.charAt(i++) - '0');
18         }
19         return base * sign;
20 
21     }
22 }

 

 
posted @ 2016-07-23 05:22  北叶青藤  阅读(222)  评论(0)    收藏  举报