java:
感谢y总❤️
class Solution {
public int myAtoi(String s) {
int len = s.length();
char[] cs = s.toCharArray();
int t = 0;
while(t < len && cs[t] == ' '){
t++;
}
if(t == len) return 0;
int m = 1;
char n = cs[t];
if(n == '+'){
t++;
}else if(n == '-'){
t++;
m = -1;
}
int res = 0;
while(t < len){
char currChar =cs[t];
if(currChar < '0' || currChar > '9'){
break;
}
if (res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE / 10 && (currChar - '0') > Integer.MAX_VALUE % 10)) {
return Integer.MAX_VALUE;
}
if (res < Integer.MIN_VALUE / 10 || (res == Integer.MIN_VALUE / 10 && (currChar - '0') > -(Integer.MIN_VALUE % 10))) {
return Integer.MIN_VALUE;
}
res = res * 10 + m * (currChar - '0');
t++;
}
return res;
}
}
python3:
正则表达式哈哈哈哈哈
class Solution:
def myAtoi(self, s: str) -> int:
return max(min(int(*re.findall('^[\+\-]?\d+', s.lstrip())), 2**31 - 1), -2**31)