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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容