Implement atoi which converts a string to an integer.
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.
Note:
Only the space character ' ' is considered as whitespace character.
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned.
Example 1:
Input: "42"
Output: 42
Example 2:
Input: " -42"
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign.
Then take as many numerical digits as possible, which gets 42.
Example 3:
Input: "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.
Example 4:
Input: "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical
digit or a +/- sign. Therefore no valid conversion could be performed.
Example 5:
Input: "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
Thefore INT_MIN (−231) is returned.
将字符串转换成int型,逻辑很简单,按照题目中一条条的写就是了,关键在于边界条件:
AC:
class Solution {
public:
int myAtoi(string str) {
if (str.empty()) {
return 0;
}
str.erase(0,str.find_first_not_of(" "));
if (1 > str.length()) {
return 0;
}
bool flag = true;
int cur = 0;
if ('-' == str[cur]) {
flag = false;
cur++;
} else if ('+' == str[cur]) {
cur++;
}
long result = 0;
while (cur < str.length() && '0' <= str[cur] && '9' >= str[cur] ) {
result = 10 * result + str[cur] - '0';
cur++;
if(result > labs(long(INT_MAX))) {
return flag ? INT_MAX : INT_MIN;
}
}
result = flag ? result : -1 * result;
return (int)result;
}
};
关于效率方面就没有什么仔细考虑了,只是单纯的写出来AC,边界这边需要注意:
- result 要考虑int型溢出,所以这里需要声明为long
long result = 0;
- 进行溢出判断时需要注意:
if(result > labs(long(INT_MAX))) {
return flag ? INT_MAX : INT_MIN;
}
另外,在网上看到另一种非常简便的写法,利用系统封装的特点:
class Solution {
public:
int myAtoi(string str) {
int out = 0;
stringstream ss;
ss << str;
ss >> out;
return out;
}
};
这里利用了输入输出流,没详细跟过具体实现,不过看起来很强大啊;
网友评论