String to Integer (atoi) - LeetCode

目录

题目链接

String to Integer (atoi) - LeetCode

注意点

  • 溢出时返回上界或下界

    解法

    解法一:从前往后,首先跳过空白字符,然后对非空白字符进行判断,如果是数字字符就转化为数字,否则就返回结果。过程中随时判断是否溢出。时间复杂度为O(n)
class Solution {
public:
    int myAtoi(string str) {
        int i = 0;
        bool positive = true;
        long long anw = 0;
        while(str[i]==' ')//跳过开头的空白字符
        {
            i++;
        }
        if(str[i] == '-')
        {
            positive = false;
            i++;
        }
        else if(str[i] == '+')
        {
            positive = true;
            i++;
        }
        else if(str[i] < '0'||str[i] > '9')
        {
            return anw;
        }
        while(str[i]!='\0'&&str[i]>='0'&&str[i]<='9')
        {
            int temp = anw*10+(str[i]-'0');
            if(anw==2147483649)
            {
                return -2147483648;   
            }
            if(temp/10 != anw)
            {
                if(positive == false)
                {
                    return -2147483648;
                }
                else
                {
                    return (int)0x7FFFFFFF;
                }
            }
            anw = temp;
            i++;
        }
        if(positive == false)
        {
            return 0-anw;
        }
        else
        {
            return anw;
        }
        
    }
};

小结

  • 思路并不难,看网上的题解需要考虑诸多边界条件,但是用我解法中这种方法就不用考虑那么多。

猜你喜欢

转载自www.cnblogs.com/multhree/p/10308570.html