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;
        }
        
    }
};

874b0eb1gy1fzgg6iqbz6j219z0k0ab5.jpg

小结

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

转载于:https://www.cnblogs.com/multhree/p/10308570.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值