标签:bsp substr .com www int none empty code bst
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
标签:bsp substr .com www int none empty code bst
原文地址:https://www.cnblogs.com/azureice/p/leetcode8.html