您的位置:首页 > 其它

Leetcode: String to Integer (atoi)

2014-12-02 15:29 253 查看
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.

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.

分析:细节题,要仔细思考input space的各种情况。解决问题的大体思路是,先略过字符串开头的若干空格,如果空格后第一个字符不是合法字符('+','-', 数字)则返回0。如果该字符为'-',记录符号为负,我们可以用一个bool变量来实现。然后再依次扫描剩下的字符,如果在数字字符出现之前出现了其他字符,则返回0。如果是数字字符串,将数字字符串转为数字。如果在数字字符串后出现了非数字字符,则结束扫描。对于数值超出int表示范围的情况,我们需要做特殊处理。代码如下:

class Solution {
public:
int atoi(const char *str) {
while(*str == ' ') str++;//skip spaces
if(*str != '+' && *str != '-' && !isdigit(*str)) return 0;//if first non-space character is not '+', '-', or digit

long long res = 0;
bool sign = true;
bool number_if = false;//whether numerical digit appears

if(*str == '-') sign = false;
if(!isdigit(*str)) str++;

//processing digit string slice
while(*str != '\0'){
if(!number_if && !isdigit(*str)) return 0;//no digits following '+' or '-'
if(number_if && !isdigit(*str)) break;//skip characters after numeric string
number_if = true;
res = 10*res + *str - '0'; //update value
//if res >= INT_MAX or res <= INT_MIN
if(res >= INT_MAX && sign){
res = INT_MAX;
break;
}else if(res >= 2147483648 && !sign){
res = 2147483648;
break;
}
str++;
}

res = sign?res:-1*res;
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: