My C++ solution


  • 0
    H
    class Solution {
    public:
        bool isPalindrome(int x) {
            if(x < 0) {
                return 0;
            }   
            int p = x, q = 0;
            while(p) {
                q = q * 10 + p % 10; 
                p /= 10; 
            }   
            return q == x;
        }
    };

  • 0
    D

    Hi, I inspirated by your code. But after careful thought, I think only need judge number x's half digital bit, there is my code : It will be faster a little

    bool isPalindrome(int x)
    {
    	if (x < 0)
    	{
    		return false;
    	}
    	if (x < 10)
    	{
    		return true;
    	}
    	if (0 == x % 10)
    	{
    		return false;
    	}
    	int newNum = 0;
    	bool bPadlin = false;
    	while (!(abs(newNum - x) < 10 || abs(newNum * 10 - x) < 10) && newNum < x)
    	{	
    		/// abs(newNum - x) < 10 --- means that number x has even digital bit, like 10, 1221...
    		/// abs(newNum * 10 - x) < 100 --- mean that number x has odd digital bit, like 121, 12321...
    		newNum = newNum * 10 + x % 10;
    		x /= 10;
    	}
    	if (abs(newNum - x) < 10)
    	{
    		if (newNum == x)
    			bPadlin = true;
    		else
    			bPadlin = false;
    	}
    	if (abs(newNum * 10 - x) < 10)
    	{
    		x /= 10;
    		if (x == newNum)
    		{
    			bPadlin = true;
    		}
    	}
    	return bPadlin;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.