题目:String to Integer (atoi)
https://leetcode.com/problems/string-to-integer-atoi/?tab=Description
问题描述:
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.
如果不考虑任意情况,默认string的字符串值含有数字,则函数非常简单。然后在此基础上分析任意字符串的处理情况。
首先,这里返回的int是32位的,所以先处理任何会超出这个上界(INT32_MAX)或下界(INT32_MIN)的整数,分别取上/下界返回。
然后要考虑字符串含有其它字符的处理:
(1)清除字符串前面的空格;
(2)前面允许出现一次“+”或“-”,但不能重复;
(3)读取完当前的数字字符后,发现下一个字符不是数字,直接返回当前的结果。
#include
#include
using namespace std;
int Myatoi(string str)
{
int n = str.length(), i = 0;
int pos = 1;
long long int num = 0;
while (str[i] == ' ') i++;
if (str[i] == '+' || str[i] == '-')
{
if (str[i] == '-') pos = -pos;
i++;
}
for (;i < n;i++)
{
if (str[i] >= 48 && str[i] <= 57)
{
if (num + pos*(str[i] - 48) > INT32_MAX) return INT32_MAX;
else if (num + pos*(str[i] - 48) < INT32_MIN) return INT32_MIN;
else num += pos*(str[i] - 48);
}
else return num;
if (str[i + 1] >= 48 && str[i + 1] <= 57)
{
if (num * 10 > INT32_MAX) return INT32_MAX;
else if (num * 10 < INT32_MIN) return INT32_MIN;
else num *= 10;
}
else return num;
}
return num;
}
int main() //test
{
string str = " -214748.3648";
int n = Myatoi(str);
cout << n << endl;
return(0);
}