您的位置:首页 > 其它

8. String to Integer (atoi)

2016-01-07 10:19 204 查看
题意描述:Implement atoi to convert a string to an integer.

需要注意的情况:

1. 正负号

2. 有效字符之前可能会有空格

3. 有效字符中出现非法字符会截断数字

4. 溢出时输出最大值或最小值

AC代码:

class Solution {
public:
int myAtoi(string str) {

if(str.length() == 0)
return 0;
int sum = 0;
int neg = 1;
int loc = 0;
while(str[loc] == ' '){
++ loc;
}
string new_str = str.substr(loc, (str.length() - loc));

for(int i = 0; i < new_str.length(); ++i){
if(i == 0 && new_str[i] == '-' || i == 0 && new_str[i] == '+'){
if(new_str[i] == '-')
neg = -1;
}else{
int num = char2num(new_str[i]);
if(num != -1){
if(sum > (0x7fffffff / 10) ){
if(neg == -1){
return (int)0x80000000;
}else{
return 0x7fffffff;
}
}else{
sum *= 10;
}
if(isAddOverflow(sum, num)){
if(neg == -1){
return (int)0x80000000;
}else{
return 0x7fffffff;
}
}else{
sum += num;
}
}else{
return sum*neg;
}
}
}
return neg*sum;
}
int  char2num(char a){

if (a >= '0' && a <= '9'){
return (a - '0');
}else{
return -1;
}
}
int isAddOverflow(int a, int b){
int c = a + b;
return ( a > 0 && b > 0 && ( c < a || c < a) || a < 0 && b < 0 && (c > b || c > a));
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: