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.
spoilers alert... click to show requirements for atoi.
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. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
题目好复杂。。。阅读理解比题目本身难多了,o(╯□╰)o
要求:
1、输入的str中开始可能由n个空格组成,去掉空格,接下来的可能是 + or - 表示符号,可能不包含符号
2、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.
str中可能包含其他字符,如 -142a34 中的a, 忽略碰到其他字符后的字符串。也就是a之后的不用算
3、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. 如果开头的空格忽略后,第一个非空字符不是0-9 或者+ - ,则字符串可能全为空或者第一个就是a等,则返回0,其实和第二条条件相似
4、越界问题,所以保存结果的用long long ans表示,注意用long也不行, long 也是32位的。
class Solution {
public:
int atoi(const char *str) {
int i=0, flag=1;
long long ans=0;
while(i<strlen(str) && str[i]==' ')
i++;
if(str[i]=='-'){
flag = -1;
i++;
}else if(str[i]=='+')
i++;
for(i;i<strlen(str);i++){
if(str[i]>='0'&&str[i]<='9'){
ans=ans*10+(str[i]-'0');
if(ans>2147483647){
if(flag==1)
return 2147483647;
else
return -2147483648;
}
}else
break;
}
return (int)(ans*flag);
}
};