Palindrome Number (Leetcode 9)

Question

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.

Solution

又是一道数学题。判断是否是回文数字,只要将数字反转即可(和string tointeger类似)。但是这里其实不用考虑溢出的问题,因为给的是一个integer,如果是回文,则反转之后一定还是原来的integer,如果溢出则一定不会是回文。负数也不是回文。

代码如下:

public class Solution {
    public boolean isPalindrome(int x) {
        if(x < 0){
            return false;
        }

        int reverse = 0;
        int temp = x;
        while(temp != 0){
            reverse = reverse * 10 + temp % 10;
            temp /= 10;
        }

        return reverse == x;
    }
}

results matching ""

    No results matching ""