码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 8. 字符串转换整数 (atoi)

时间:2020-01-05 09:26:29      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:math   mat   运行时   忽略   long   运行时间   etc   min   区别   

题意

实现一个atoi函数,具体功能如下:

  1. 丢弃开头无用的空格,直到找到第一个非空格的字符为止。
  2. 当寻找到的第一个非空字符为正负号时或数字时,将其与后面尽可能多的连续数字组合起来形成整数。剩余的部分忽略。
  3. 如果第一个字符非上面三种情况时,则返回0。
  4. 如果数值超过了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)。

LeetCode 8. 字符串转换整数 (atoi)

标签:math   mat   运行时   忽略   long   运行时间   etc   min   区别   

原文地址:https://www.cnblogs.com/songjy11611/p/12151054.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!