Palindrome Number

来源:互联网 发布:googlenet tensorflow 编辑:程序博客网 时间:2024/06/08 09:31

Determine whether an integer is a palindrome. Do this without extra space.

click to show spoilers.

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.

这道题因为简单一直没有写下来,今天做了一下,发现了一个容易越界的情况:就是在判断divisor大小的时候,开始直接算了x/(divisor*10)>0,这样在一个情况下比如x=1000000001(位数和Integer.MAX_VALUE)相等,在d=100000000(与最大值位数相等,但是如果*10就会越界)时,d*10=1410065408 所以就要做x/divisor >= 10的判断

    public boolean isPalindrome(int x) {        if (x < 0) {            return false;        }        int divisor = 1;        while(x/divisor >= 10) {            divisor *= 10;        }        while (divisor > 0) {            if (x%10 == x/divisor) {                x %= divisor;                x /= 10;            } else {                return false;            }            divisor /= 100;        }        return true;    }


0 0
原创粉丝点击