Palindrome Number

 Total Accepted: 54885 Total Submissions: 185086My Submissions

Question Solution 


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.


Show Tags

分析:负数不是回文数字,而且题目要求不能有额外的空间,因此不能以字符串形式存储,因此可以=比对首位两个数字是否相等,比对后去除首尾数字,然后依次迭代,直到只剩1个数字或是不剩数字,返回结果


public class Solution {

    public boolean isPalindrome(int x) {

        if(x<0)

            return false;

            

        int p=1;

        while(x/p>=10)

            p=p*10;

        int q=10;

        while(p>1)

        {

            if(x/p!=x%q)

                return false;

            else

            {

                x=x%p;

                x=x/q;

                p=p/100;

            }

        }

        return true;

    }

}