string to integer (atoi)
private static final int maxDiv10 = Integer.MAX_VALUE / 10;
public int atoi(String str) {
int i = 0, n = str.length();
while (i < n && Character.isWhitespace(str.charAt(i))) i++;
int sign = 1;
if (i < n && str.charAt(i) == '+') {
i++;
} else if (i < n && str.charAt(i) == '-') {
sign = -1;
i++;
}
int num = 0;
while (i < n && Character.isDigit(str.charAt(i))) {
int digit = Character.getNumericValue(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;
}
- 正负
- overflow (max int, min int)
- trim white spaces
- 特殊notation:科学计数法,0xFFFF…
- 12314abcdse, 是否保留合法的12314然后丢弃后面
- invalid conversion 返回什么值
valid number
public boolean isNumber(String s) {
int i = 0, n = s.length();
while (i < n && Character.isWhitespace(s.charAt(i))) i++;
if (i < n && (s.charAt(i) == '+' || s.charAt(i) == '-')) i++;
boolean isNumeric = false;
while (i < n && Character.isDigit(s.charAt(i))) {
i++;
isNumeric = true;
}
if (i < n && s.charAt(i) == '.') {
i++;
while (i < n && Character.isDigit(s.charAt(i))) {
i++;
isNumeric = true;
}
}
while (i < n && Character.isWhitespace(s.charAt(i))) i++;
return isNumeric && i == n;
}
corner test cases:
“0.1”, “abc”, ” 123 “,”12 3”, “123abc”, “+1”, “-1”, “0xFFF”, “1e10”(1*10^10)
reverse integer
public int reverse(int x) {
int ret = 0;
while (x != 0) {
// handle overflow/underflow
if (Math.abs(ret) > 214748364) {
return 0;
}
ret = ret * 10 + x % 10;
x /= 10;
}
return ret;
}
test cases:
“-123”, “1000”, overflow after reversion
plus one
public void plusOne(List<Integer> digits) {
for (int i = digits.size() - 1; i >= 0; i--) {
int digit = digits.get(i);
if (digit < 9) {
digits.set(i, digit + 1);
return;
} else {
digits.set(i, 0);
}
}
digits.add(0);
digits.set(0, 1);
}
Could the number be negative?
How are the digits ordered in the list?
palindrome number
public boolean isPalindrome(int x) {
if (x < 0) return false;
int div = 1;
while (x / div >= 10) {
div *= 10;
}
while (x != 0) {
int l = x / div;
int r = x % 10;
if (l != r) return false;
x = (x % div) / 10;
div /= 100;
}
return true;
}