LeetCode No.9 Palindrome Number | #math #digit manipulation

Q:

Determine whether an integer is a palindrome. Do this without extra space.
Some hints:Could negative integers be palindromes? (ie, -1) If you are thinking of converting the integer to string, note the restriction of using extra space. You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case? There is a more generic way of solving this problem.

A:

public class Solution {
    public boolean isPalindrome(int x) {
        if(x < 0) return false;
        int num = x;
        int res = 0;
        while(num != 0) {
            res = res * 10 + num % 10;
            num /= 10;
        }
        return x == res;
    }
}

大多数ACed solutions都直接判定负数input返回false,好像这不算是什么handling overflow吧。如果输入一个negative signed integer,我觉得先把它的负号处理掉,变成绝对值后的数字,然后再进入while loop进行判定。

其它人关于negative number if palindrome这个问题的讨论

顺便看下这道题:No.7 Reverse Integer

你可能感兴趣的:(LeetCode No.9 Palindrome Number | #math #digit manipulation)