Palindrome Number Leetcode

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.

一开始用string做的,做完才发现不能用string?

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

这个方法也挺巧妙的,只是要考虑当一个digit后面都是0的时候x / 10也会变成0,所以要一开始就去掉这种情况。

posted @ 2017-01-26 05:37  璨璨要好好学习  阅读(104)  评论(0编辑  收藏  举报