思路:模拟
考虑:
class Solution { public: int strToInt(string str) { int i=0,sign=1; while(i<str.size()&&str[i]==' ')i++; if(i==str.size())return 0; if(str[i]=='-'){ sign=-1; i++; } else if(str[i]=='+'){ i++; } int res=0; while(i<str.size()){ if(str[i]<'0'||str[i]>'9')break; if(res>INT_MAX/10||(res==INT_MAX/10&&str[i]>'7'))return sign==-1?INT_MIN:INT_MAX; res=res*10+(str[i]-'0'); i++; } return sign*res; } };
时间复杂度 O(n)
空间复杂度 O(1)