LeetCode -- Palindrome Number

相似题目:

Palindrome Number

Valid PalinDrome

Reverse Linked List

  Palindrome Linked List

Question:

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

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.

Analysis:

思路一:转化为字符串,但是题目要求不能占用额外的空间,故不可行;

思路二:将数字倒置,容易导致溢出。

思路三:分别从数字的左边和右边对数字进行处理,若碰到不相等的数字,即可返回false,若一直比较只最后,则说明该数字是回文数字。

Answer:

    public boolean isPalindrome(int x) {
        if(x < 0)
            return false;
        
        int dec = judgeDec(x);
        int sdec = 10;
        
        while(x != 0) {
            int big = x / dec;
            int small = x % sdec;
            if(big != small)
                return false;
            //x = (x % dec) / 10;
            x = x % dec;
            x = x / 10;
            dec = dec / 100;
        }
        return true;
    }
    
    
    public int judgeDec(int num) {
        int wei = 1;
        while(num / wei >= 10) {
            wei *= 10;
        }
        return wei;
    }
原文地址:https://www.cnblogs.com/little-YTMM/p/4794568.html