String to Integer (atoi)
题目:
Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
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.
Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.
题意:
字符串转化为整型,很常见的一个题,就是考虑的情况比较多而已,题目给了那么长一段话也是告诉你要考虑的情况会很多。
思路:
考虑的情况如下:
1.” 123456” 输出:123456
2.”u123456” 输出:123456
3.”123 123” 输出:123
4.”—123456” 输出:123456
5.”+-2” 输出:-2 , 测试leetcode输出是0
6.”-+2” 输出:-2 , 测试leetcode输出是0,实际int i = +-2,输出i的确是-2。
7.”—-u123456” 输出:123456
8.”-111111111111” 输出:-2147483648
9.”111111111111” 输出:2147483647
先提取出连续的数字字符串,然后判断负号的个数,判断是否越界等等,其实也就是考虑情况多一些,我考虑的情况和leetcode有出入,并没有通过,仅供参考。
代码:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string>
#include <iostream>
#include <cmath>
using namespace std;
int myAtoi(string str)
{
string s = "0123456789";
if(str.size() == 0)
return 0;
//截取出字符串,不应该有0
auto beg = str.find_first_of("123456789");
if(beg >= str.size())
return 0;
auto end = beg+2;
while(1)
{
if(str[end] >= 48 && str[end] <= 57)
{
++end;
}else
{
break;
}
}
auto ret = str.substr(beg, end-beg);
int flag = 0;
//找寻负号的个数,判断正负
for(int i = 0; i <= beg; ++i){
if(str[i] == '-')
{
flag++;
}
}
//如果数字位数超过最大值位数,越界,判断正负后直接返回
if(ret.size() > 10)
{
if(flag%2 == 1){
return -2147483648;
}else{
return 2147483647;
}
}
//声明为double因为double范围大可以找到越界的情况
double d = 0;
int t = ret.size()-1;
//字符串转化为整型
for(char a:ret)
{
d += (a-48)*pow(10,t);
t--;
}
//转化正负
if(flag%2 == 1)
d = -d;
//判断是否数字位数相等且越界越界,越界返回最大或者最小值
if(d > 2147483647){
return 2147483647;
}else if(d < -2147483648){
return -2147483648;
}else{
//将double转换为int返回
return static_cast<int>(d);
}
return 0;
}
int main(int argc, char *argv[])
{
cout << myAtoi(" 123456") << endl;
cout << myAtoi("u123456") << endl;
cout << myAtoi("123 123") << endl;
cout << myAtoi("---123456") << endl;
cout << myAtoi("+-2") << endl;
cout << myAtoi("-+2") << endl;
cout << myAtoi("----u123456") << endl;
cout << myAtoi("-111111111111111") << endl;
cout << myAtoi("111111111111111") << endl;
return EXIT_SUCCESS;
}
运行结果: