• String to Integer (atoi)


    题目链接

    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]!=''&&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;
            }
            
        }
    };
    

    小结

    • 思路并不难,看网上的题解需要考虑诸多边界条件,但是用我解法中这种方法就不用考虑那么多。
  • 相关阅读:
    app测试点-1
    毕业5年的感悟
    关于游戏外挂
    python-unittest单元测试框架
    python-requests
    http简介
    python基础-发邮件smtp
    python-加密
    4 Python 日期和时间
    5 Python 数据类型—数字
  • 原文地址:https://www.cnblogs.com/multhree/p/10308570.html
Copyright © 2020-2023  润新知