题意
实现一个atoi
函数,具体功能如下:
- 丢弃开头无用的空格,直到找到第一个非空格的字符为止。
- 当寻找到的第一个非空字符为正负号时或数字时,将其与后面尽可能多的连续数字组合起来形成整数。剩余的部分忽略。
- 如果第一个字符非上面三种情况时,则返回0。
- 如果数值超过了int的范围则返回INT_MAX或INT_MIN。
思路
- 直接模拟,注意细节就好了。时间复杂度\(O(n)\)。
代码
class Solution { public: int myAtoi(string str) { int len = str.size(), st = 0; for(int i = 0; i < len; ++i) if(str[i] != ' ') { st = i; break; } //cout << st << ' ' << str[st] << endl; bool flag = true; if(str[st] == '+') ++st; else if(str[st] == '-') { flag = false; ++st; } //cout << flag << endl; int res = 0; if(isdigit(str[st])) { while(st < len && isdigit(str[st])) { //cout << "res = " << res << endl; int add = str[st++] - '0'; if( flag && ( res > INT_MAX / 10 || ( res == INT_MAX / 10 && add >= 7))) return INT_MAX; if(!flag && (-res < INT_MIN / 10 || (-res == INT_MIN / 10 && add >= 8))) return INT_MIN; res = res * 10 + add; //cout << res << ' ' << add << ' ' << st << endl; } //cout << res << endl; if(!flag) res = -res; return res; } else return 0; } };
总结
运行时间只击败了60%的用户。。看了下最快的代码,思路没啥区别,就是少了几个判断,没必要再“优化”了。
如:中间的存储答案的变量是用的long
(我一开始也打算用long的)、判断符号位直接用的int
(符号和正号的ASSIC码正好差2——用44 - str[i]
正好等于1或-1)。
来源:https://www.cnblogs.com/songjy11611/p/12151054.html