leetcode——String to Integer

来源:互联网 发布:淘宝折扣网站 编辑:程序博客网 时间:2024/06/06 08:46

问题

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

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

思路

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

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

需要注意比较多的细节

  • 删掉起始空格
  • 正符号判断
  • 删掉有效字符(0-9数字字符)后面的所有无效字符
  • 整数是否溢出

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

解决

#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 会发生溢出。

0 0
原创粉丝点击