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.
// string_to_int.cpp : 定义控制台应用程序的入口点。
//将string转化为int,注意点是考虑到所有可能的输入情况
#include "stdafx.h"
#include<iostream>
using namespace std;
int MyAtoi(string s)
{
int L = s.size();
int result = 0;
//输入为空
if (L == 0)
{
return 0;
}
int k; int flag = 0;
for (int i = 0; i < L; i++)
{
//输入为负数- ,输入+
if (s[i] == '-'&& result == 0 )
{
if (flag == 0)
{
flag = -1;
continue;
}
else
return 0;
}
if (s[i] == '+'&&result == 0)
{
if (flag == 0)
{
flag = 1;
continue;
}
else
return 0;
}
//输入非数字字符
if ((s[i]>'9' || s[i] < '0')&&s[i]!=' ')
{
if (flag >= 0)
return result;
else
return -result;
}
else if (s[i] == ' ')
{
if (flag == 0&&result ==0)
continue;
else
return result;
}
else
{
k = s[i] - '0';
//string转化为int越界
if (result > INT_MAX / 10 || (result == INT_MAX/10 && k > INT_MAX % 10))
{
if (flag >= 0)
return INT_MAX;
else
return INT_MIN;
}
result = result * 10 + k;
}
}
if (flag >= 0)
return result;
else
return -result;
}
int main(int argc, _TCHAR* argv[])
{
cout << MyAtoi("123 456");
return 0;
}
这个题目想的就是特殊输入情况,题目测试用例很全面,但是问题也就随之出现。很多有歧义的例子。这就看个人理解了。当然重点是要考虑到这些方面,至于怎么样处理,那仁者见仁智者见智。