Leetcode string and integer 问题

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值