您的位置:首页 > 其它

8. String to Integer (atoi) (重要)

2016-07-11 19:40 295 查看
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.

注意5点。

1.空字符串

2.字符串前的空格

3.+-号

4.非法字符(这里返回非法字符前的有效位)

5.溢出(这里如果大于最大,返回最大;小于最小返回最小)

class Solution {
public:
int myAtoi(string str) {
int len = str.size();
if (len == 0) return 0;

long long sum = 0;
int i = 0;
while (str[i] == ' ') i++;

int minus = 1;
if (str[i] == '-'){
minus = -1;
i++;
}
else if (str[i] == '+'){
i++;
}

for (; i < len; i++){
if (str[i]<'0' || str[i]>'9'){
break;
}
sum = sum*10 + (str[i] - '0')*minus;
if (sum>INT_MAX){
return INT_MAX;
}
else if (sum < INT_MIN){
return INT_MIN;
}
}
return sum;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: