leetcode -- Palindrome Number

Palindrome Numberthis

Some hints:

Could negative integers be palindromes? (ie, -1)spa

If you are thinking of converting the integer to string, note the restriction of using extra space.rest

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?code

There is a more generic way of solving this problem.ip

public boolean isPalindrome ( int x ) {
        if ( x>= 0 && x <= 9 ){
            return true;
        }

        if ( x<0 ){
            return false;
        } else if ( x >= 10 &&  x%10 == 0 ){
            return false;
        }

        int y = x;
        int sum = 0;

        while ( x != 0 ){
            sum = 10*sum + ( x%10 );
            x = x/10;
        }

        return y == sum;
    }

First, if x is smaller than 0, x is not a palindrome.leetcode

We define a value sum, and add the values of x from low, if new sum equals to y, then x is a palindrome.get

相關文章
相關標籤/搜索