首页 > 代码库 > Leetcode: String to Integer

Leetcode: String to Integer

抠细节的题目,很多次过,特别是 Integer.MIN_VALUE 与 Integer.MAX_VALUE的绝对值并不一样大

 1 public class Solution {
 2     public int atoi(String str) {
 3         int result=0;
 4         int i, j;
 5         boolean isNeg=false;
 6         char c, t;
 7         if(str==null) return 0;
 8         for(i=0; i<str.length(); i++){//find first sequence of non-whitespace characters
 9             c=str.charAt(i);
10             if(c==‘ ‘) continue;
11             if(c==‘-‘){
12                 isNeg=true;
13                 i++;
14                 break;
15             }
16             if(c==‘+‘){
17                 i++;
18                 break;
19             }
20             if(c>=‘0‘&&c<=‘9‘) break;
21             if(c<‘0‘||c>‘9‘) return 0;
22         }
23         for(j = i; j < str.length(); ++j){
24             t=str.charAt(j);
25             if(t<‘0‘||t>‘9‘) break;
26             if((Integer.MAX_VALUE-(int)(t-‘0‘))/10 < result && !isNeg){
27                 return Integer.MAX_VALUE;
28             }
29             if((Integer.MAX_VALUE-(int)(t-‘0‘))/10 < result && isNeg){
30                 return Integer.MIN_VALUE;
31             }
32             result=result*10+(int)(t-‘0‘);
33         }
34         return isNeg? (-1)*result:result;
35     }
36 }

转载一个不错的c++解法:

class Solution {
public:
    int atoi(const char *str) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        while (isspace(*str)) str++;
        int ret = 0;
        bool isNeg = false;
        if (*str == ‘+‘) str++;
        if (*str == ‘-‘) {
            isNeg = !isNeg;
            str++;
        }
        while (isdigit(*str)) {
            if (ret > (INT_MAX - int(*str-‘0‘))/10) return isNeg? INT_MIN : INT_MAX;
            ret = ret*10+int(*str-‘0‘);
            str++;
        }
        return isNeg? -ret : ret;
    }
};