LeetCode 8. String to Integer (atoi)

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.

解析:
将给定的字符串转换为整数,功能类似于atoi。
因为输入时字符串,所以需要考虑的情况比较多。具体说来:
1.字符串可能以空格开始,需要从第一个非空字符开始计算。
2.允许数字以正负号开头。
3.遇到非法字符便停止转换,返回当前已经转换的值,如果开头就是非法字符则返回0。
4.转换的整数越界,停止处理返回0。
具体代码如下:
[cc lang=”C++”]
class Solution {
public:
int myAtoi(string str) {
int length = str.length();
long result = 0;
int flag = 1;
if(length <= 0 ) return 0; int index = str.find_first_not_of(' ');//第一个非空字符开始 for(int i=index; i < length; i++) { if(str[i] == '-') { if(i+1=’0′ && str[i+1] <='9'))//前一个字符为负,后一个非0-9 return 0; flag = -1; }else if(str[i] == '+') { if(i+1=’0′ && str[i+1] <='9')) return 0; }else if(str[i] >=’0′ && str[i] <= '9') { result = result*10 + (str[i]-'0'); if(result*flag > INT_MAX)//判断数值越界的情况
return INT_MAX;
if(result*flag < INT_MIN) return INT_MIN; }else{ break; } } return result * flag; } }; [/cc] update in 2019.5.25 另一个版本的代码,代码看上去更加简洁。 [cc lang="C++"] class Solution { public: int myAtoi(string str) { int sign = 1, base = 0, i = 0; while (str[i] == ' ') { i++; } if (str[i] == '-' || str[i] == '+') { sign = 1 - 2 * (str[i++] == '-'); } while (str[i] >= ‘0’ && str[i] <= '9') { if (base > INT_MAX / 10 || (base == INT_MAX / 10 && str[i] – ‘0’ > 7)) {
if (sign == 1) return INT_MAX;
else return INT_MIN;
}
base = 10 * base + (str[i++] – ‘0’);
}
return base * sign;
}
};
[/cc]
主要解释一下条件里面的 str[i] – ‘0’ > 7
因为INT_MAX= 2147483647,最后一位数是7,如果超过7则会出现溢出的情况。

Add a Comment

邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据