美文网首页
8. String to Integer (atoi)

8. String to Integer (atoi)

作者: yansh15 | 来源:发表于2017-07-10 22:06 被阅读0次

题目描述

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)

相关文章

网友评论

      本文标题:8. String to Integer (atoi)

      本文链接:https://www.haomeiwen.com/subject/klbuhxtx.html