您的位置:首页 > 其它

leetcode——String to Integer

2016-02-20 22:02 405 查看

问题

实现自己的 atoi 字符转换函数。

一直以来都有听说过在面试过程中会问到实现 atoi 函数,现在碰到这题,正好拿来练练手。

思路

核心思路就一条语句:(m 为要返回的整数)

[code]m = m * 10 + str[i] - ‘0’;


需要注意比较多的细节

删掉起始空格

正符号判断

删掉有效字符(0-9数字字符)后面的所有无效字符

整数是否溢出

围绕着那条核心语句,一点点将上述四点条件考虑进去,可以写出如下的实现代码:

解决

[code]#include<iostream>
#include<string>
using namespace std;

int myAtoi(string str) {
    int m = 0;
    int flag = 1;

    std::size_t found = str.find_first_not_of(' ');
    //cout << "found is: " << found << endl;
    if(str[found] == '-' || str[found] == '+') {
        if (str[found] == '-')
            flag = -1;
        found++;
    }

    for(size_t i = found; i < str.size(); i++) {
        if(str[i] >='0' && str[i] <= '9') {
            if (m > 214748364) {
                if(flag == 1)
                    return 2147483647;
                else return -2147483648;
            }
            if (m == 214748364) {
                if (flag == 1 && str[i] - '0' > 7)
                    return 2147483647;
                if (flag == -1 && str[i] - '0' > 8)
                    return -2147483648;
            }
            m = m * 10 + str[i] - 48;
        }
        else {
            if (m == 0)
                return 0;
            else if(m != 0) {
                if (flag == -1)
                    return -m;
                return m;
            }
        }

    }
    if (flag == -1)
        return -m;
    return m;
}

int main() {
    cout << "result : " << myAtoi("    -114321")  << endl;
    cout << "result : " << myAtoi("    -114321aaaa")  << endl;
    cout << "result : " << myAtoi("  -  114321aaaa")  << endl;
    cout << "result : " << myAtoi(" asf 123341asdf")  << endl;
    cout << "result : " << myAtoi("+1") << endl;
    cout << "result : " << myAtoi("-004152aaaa111") << endl;
    cout << "-2147483648 : " << myAtoi("-2147483648") << endl;
    cout << "-2147483649 : " << myAtoi("-2147483649") << endl;
    cout << "2147483647 : " << myAtoi("2147483647") << endl;
    cout << "2147483648 : " << myAtoi("2147483648") << endl;
    cout << "      -11919730356x : " << myAtoi("      -11919730356x") << endl; 
    return 0;
}


另外值得注意的是代码中的数字
2147483647
可由
-((1<<31) + 1))
得到,并将其设定为一个变量 MAX。而
214748364
则可由
MAX%10
得到,这样能够增加程序的可读性与自动性。

因为
1<<31
的值为
-2147483648
(1<<31) * 2
会发生溢出。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: