String to Integer (atoi)
Implement atoi
which converts a string to an integer.
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned.
本题题意是要自己写一个atoi函数(将字符串转换成整数),思想很简单,关键是有几处细节需要考虑:
1.数字前面有空格,如s=" 123456",空格需舍弃。
2.数字前出现了不必要或多于的字符导致数字认证错误,输出0。如s=" b1234",s=" ++1233", s=" +-1121"。
3.数字中出现了不必要的字符,返回字符前的数字。如s=" 12a1", s=" 123 123"。
4.数字越界,超过了范围(-2147483648--2147483647),分别返回-2147483648和2147483647。
Answer:
class Solution
{
public:
int myAtoi(string str)
{
if(str == "")
return 0;
int i = 0;
long long res = 0;
while(str[i] != '\0' && str[i] == ' ')
{
i ++;//舍弃前面空格
}
int flag = 1;
if(str[i] == '-')//确定正负
{
flag = -1;
i ++;
}
else if(str[i] == '+')
{
i ++;
}
while(str[i] != '\0')
{
if(str[i] >= '0' &&str[i] <= '9')
{
res = res*10 + str[i] - '0';
if(res > INT_MAX)
{
if(flag == 1)
return INT_MAX;
else
return INT_MIN;
}
i ++;
}
else break;
}
res = flag * res;
return (int)res;
}
};