您的位置:首页 > 编程语言 > C语言/C++

LeetCode String to Integer (atoi) c++

2015-11-19 16:55 495 查看
首先总结下做题的过程,最开始我又忘记了应该先明确思路再写代码的信条,写一点提交一次,改一次,效率极低,直到自己崩溃,推翻重做。

问题分析(题目中有)

String转int

考虑空格问题

考虑+,-号问题

考虑整型越界问题

解决办法

考虑从前遍历还是从后遍历

空格问题

空格在数字前:跳过

空格在数字中间:跳出

+号问题:在数字前跳过即可,在数字中跳出

-号问题:在数字前,记录,最后结果*-1,在数字中跳出

非数字、+、-、“ ”的直接跳出即可,返回0

越界问题

使用64位整型longlong(VC6.0中使用__int64 ,longlong是C99中的)

当结果大于INTMAX或者小于INTMIN分别返回INTMAX和INTMIN

结果的判断在计算过程中,每次判断,如果越界,判断结果的正负,然后返回相应的临界值。

具体代码

#include<iostream>
#include <string>
#include <math.h>
using namespace std;

int myAtoi(string str) {
int i = 0;
int sign = 1;
__int64 result = 0;
//long long result = 0;

while(str[i]==' ')
{
i++;
}
if (str[i] == '+')
{
i++;
}
else if (str[i] == '-')
{
sign = -1;
i++;
}

if (str[i]>=48&&str[i]<=57)
{//遇到第一个数字遍历后边的内容
for (int j = i;j<str.length();j++)
{
if (str[j]>=48&&str[j]<=57)
{
result = result*10 + (str[j]-48);
if (result>INT_MAX||result<INT_MIN)
{
if (sign == 1)
{
return INT_MAX;
}
else
{
return INT_MIN;
}
}
}
else
{//如果遇到非数字的,跳出
break;
}
}

}

return sign*result;
}

int main()
{
string str1 = "123456";
cout<<myAtoi(str1)<<endl;
string str2 = "+";
cout<<myAtoi(str2)<<endl;
string str3 = "+1";
cout<<myAtoi(str3)<<endl;
string str4 = "    010";
cout<<myAtoi(str4)<<endl;
string str5 = " +004500";
cout<<myAtoi(str5)<<endl;
string str6 = " +-2";
cout<<myAtoi(str6)<<endl;
string str7 = "  -0012a42";
cout<<myAtoi(str7)<<endl;
string str8 = "-2147483649";
cout<<myAtoi(str8)<<endl;
string str9 = "2147483648";
cout << myAtoi(str9) << endl;
string str10 = "123 456";
cout << myAtoi(str10) << endl;
string str11 = " -11919730356x";
cout << myAtoi(str11) << endl;
string str12 = "9223372036854775809";
cout << myAtoi(str12) << endl;
string str13 = "-1";
cout << myAtoi(str13) << endl;
string str14 = "18446744073709551617";
cout << myAtoi(str14) << endl;
return 0;
}


欢迎交流讨论
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode atoi