class Solution {
public int reverse(int x) {
int rev = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;
if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
rev = rev * 10 + pop;
}
return rev;
}
}
复制代码
字符串提出整数
基本都可以通过Jdk解决转化,考虑的问题依然是越界
class Solution {
private static final int maxDiv10 = Integer.MAX_VALUE / 10;
public int myAtoi(String str) {
int i = 0;
int n = str.length();
while (i < n && Character.isWhitespace(str.charAt(i))) {
i++;
}
int sign = 1;
if (i < n && str.charAt(i) == '+') {
i++;
}
if (i < n && str.charAt(i) == '-') {
sign = -1;
i++;
}
int num = 0;
while (i < n && Character.isDigit(str.charAt(i))) {
int digit = Character.getNumbericValue(str.charAt(i));
if (num > maxDiv10 || num == maxDiv10 && digit >= 8) {
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
num = num * 10 + digit;
i++;
}
return sign * num;
}
}
复制代码