LeetCode 7 -- String to Integer (atoi)

Implement atoi to convert a string to an integer.


转换很简单,唯一的难点在于需要开率各种输入情况,例如空字符串,含有空格,字母等等。

另外需在写的时候注意细节问题,完成后需要反复调试,整合。

 1 public class Solution {
 2     public int myAtoi(String str) {
 3         if (str == null || str.length() < 1)
 4         return 0;
 5  
 6     str = str.trim();
 7  
 8     char flag = '+';
 9  
10     int i = 0;
11     if (str.charAt(0) == '-') {
12         flag = '-';
13         i++;
14     } else if (str.charAt(0) == '+') {
15         i++;
16     }
17     double result = 0;
18  
19     while (str.length() > i && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
20         result = result * 10 + (str.charAt(i) - '0');
21         i++;
22     }
23  
24     if (flag == '-')
25         result = -result;
26 
27     if (result > Integer.MAX_VALUE)
28         return Integer.MAX_VALUE;
29  
30     if (result < Integer.MIN_VALUE)
31         return Integer.MIN_VALUE;
32  
33     return (int) result;        
34     }
35 }
原文地址:https://www.cnblogs.com/myshuangwaiwai/p/4512377.html