力扣题-12.20
力扣题1:8. 字符串转换整数 (atoi)
解题思想:遍历字符串,通过限制返回条件进行解题
class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
res = 0
i = 0
sign = 1
if not str: return 0
while str[i] == ' ':
i += 1
if i == len(str): return 0
if str[i] == '-':
sign = -1
if str[i] in '+-':
i += 1
for j in range(i,len(str)):
if not '0' <= str[j] <= '9' : break
res = 10 * res + ord(str[j]) - ord('0')
return max(min(sign * res, 2**31 - 1), -2**31)
class Solution {
public:
int myAtoi(string str) {
int res = 0;
int i = 0;
int sign = 1;
if (str.empty()) {
return 0;
}
while (str[i] == ' ') {
i++;
if (i == str.length()) {
return 0;
}
}
if (str[i] == '-') {
sign = -1;
}
if (str[i] == '+' || str[i] == '-') {
i++;
}
for (int j = i; j < str.length(); j++) {
if (!isdigit(str[j])) {
break;
}
if (res > (INT_MAX - (str[j] - '0')) / 10) {
return (sign == 1) ? INT_MAX : INT_MIN;
}
res = 10 * res + (str[j] - '0');
}
return sign * res;
}
};