8. String to Integer (atoi)

题目描述

Implement atoi to convent a string to an integer.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

输入与输出

class Solution {
public:
    int myAtoi(string str) {
        
    }
};

样例

题目中没有样例,提供一些测例。

Input Output
"" 0
"+" 0
"+-2" 0
"-+5" 0
" -0012a42" -12
"-2147483648" -2147483648
"2147483648" 2147483647

题解与分析

功能自身不难实现,需要考虑较多的边界情况。(自己的实现不是很优雅>_<)

C++ 代码如下:

class Solution {
public:
    int myAtoi(string str) {
        if (str.empty())
            return 0;
        int index = 0;
        long long num = 0;
        bool negative = false;
        while (str[index] == ' ')
            ++index;
        if (str[index] == '+' || str[index] == '-')
            negative = (str[index] == '-'), ++index;
        for ( ; index < str.size() && str[index] >= '0' && str[index] <= '9'; ++index) {
            num = num * 10 + str[index] - '0';
            if (num > (long long)INT_MAX + 10)
                break;
        }
        num = negative ? -num : num;
        if (num > INT_MAX)
            num = INT_MAX;
        if (num < INT_MIN)
            num = INT_MIN;
        return num;
    }
};

该解法的时间复杂度为 O(n)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容