String to Integer (atoi)
Solution 1
这个题和Question 6其实考察的内容一样,都是对整数的按位处理,以及溢出时的额外判断。因为都是上一个题有过的策略,因此在这里不做详细描述了。根据本题的额外要求,就是要判断数字前面是否只有空格字符,以及没有有效数字的情形。
- 时间复杂度: O ( n ) O(n) O(n), n n n为字符串到数字结尾的长度
- 空间复杂度: O ( 1 ) O(1) O(1),仅维护常数个变量
class Solution {
public:
int myAtoi(string s) {
int ans = 0;
int pos = 0;
bool plus = true;
// whitespace
while (pos < s.size() && s.at(pos) == ' ') {
pos ++;
}
if (pos >= s.size()) {
// all whitespaces
return 0;
}
else if (s.at(pos) != '+' && s.at(pos) != '-' && s.at(pos) < '0' && s.at(pos) > '9') {
// first non-whitespce is not a number or sign
return 0;
}
// sign
if (s.at(pos) == '+' || s.at(pos) == '-') {
plus = s.at(pos) == '+' ? true : false;
pos ++;
}
while (pos < s.size() && s.at(pos) >= '0' && s.at(pos) <= '9') {
int current = s.at(pos) - 48;
// overflow?
if (ans > INT_MAX / 10 || (ans == INT_MAX / 10 && current > 7)) {
return plus? INT_MAX : INT_MIN;
}
ans = ans * 10 + current;
pos ++;
}
if (!plus) {
ans *= -1;
}
return ans;
}
};
Solution 2
Solution 1的Python实现,这里不需要对负数取余,因此没有特别多的注意事项,此外Python有很多非常方便的字符串处理函数。
class Solution:
def myAtoi(self, s: str) -> int:
# whitespace
s = s.strip()
if len(s) == 0:
return 0
# other non-whitespace character
if s[0] != '+' and s[0] != '-' and not s[0].isdigit():
return 0
sign = True
ans = ''
# sign
if s[0] == '+' or s[0] == '-':
sign = True if s[0] == '+' else False
s = s[1:]
for c in s:
if not c.isdigit():
break;
else:
ans += c
if len(ans) == 0:
return 0
ans = int(ans)
if not sign:
ans *= -1
if ans > 2**31 -1 or ans < 2 ** 31 * -1:
ans = 2**31 -1 if ans > 2**31 -1 else 2**31 * -1
return ans