1. 程式人生 > >leetcode 8 字符串轉整數

leetcode 8 字符串轉整數

while sign 代碼 public www. str res base result

class Solution {
public:
    int myAtoi(string str) {
        int sign=0;
        int firstNonSpace;
        int lastNonSpace;
        
        for(firstNonSpace=0;firstNonSpace<str.size();firstNonSpace++){
            if(str[firstNonSpace]!= ){
                break;
            }
        }
        
if(firstNonSpace==str.size()){ return 0; } else{ if(str[firstNonSpace]==+){ firstNonSpace++; } else if(str[firstNonSpace]==-){ sign=1; firstNonSpace++; } if(firstNonSpace==str.size()){
return 0; } if((str[firstNonSpace]<0)||(str[firstNonSpace]>9)){ return 0; } for(lastNonSpace=firstNonSpace;lastNonSpace<str.size();){ if((str[lastNonSpace]>=0)&&(str[lastNonSpace]<=
9)){ lastNonSpace++; } else{ break; } } if(lastNonSpace-firstNonSpace>10){ if(sign==0){ return INT_MAX; } else{ return INT_MIN; } } if(lastNonSpace-firstNonSpace==10){ if(sign==0&&str.substr(firstNonSpace,lastNonSpace-firstNonSpace)>="2147483647"){ return INT_MAX; } else if(sign==1&&str.substr(firstNonSpace,lastNonSpace-firstNonSpace)>="2147483648"){ return INT_MIN; } } int result=0; for(int i=firstNonSpace;i<lastNonSpace;i++){ result=(str[i]-0)+result*10; } if(sign==0){ return result; } else{ return -result; } } } };

擊敗30%。

然後我今天又交了一次,沒過。

" 0000000000012345678"

別人的代碼:

class Solution {
public:
    int myAtoi(string str) {
        if (str.empty()) return 0;
        int sign = 1, base = 0, i = 0, n = str.size();
        while (i < n && str[i] ==  ) ++i;
        if (str[i] == + || str[i] == -) {
            sign = (str[i++] == +) ? 1 : -1;
        }
        while (i < n && str[i] >= 0 && str[i] <= 9) {
            if (base > INT_MAX / 10 || (base == INT_MAX / 10 && str[i] - 0 > 7)) {
                return (sign == 1) ? INT_MAX : INT_MIN;
            }
            base = 10 * base + (str[i++] - 0);
        }
        return base * sign;
    }
};

來自:http://www.cnblogs.com/grandyang/p/4125537.html

leetcode 8 字符串轉整數