Simple C code beats 94% submissions.


  • 1
    B
    bool isPalindrome(int x) {
    if (x < 0) return false;
    int mirror = 0;
    int cache = x;
    while (x) {
        mirror = mirror*10+x%10;
        x/=10;
    }
    return mirror == cache;
    

    }


  • 0
    D

    how do you cope with the overflow of the "mirror"?


  • 0
    B

    thanks for your reply ! that's a good point that the mirror will be overflow if x is special. One solution is to use "long" instead of "int" for "mirror". Thank you for pointing this out !


  • 0
    B

    @binchan that's no problem, we can just think like that, only when n is not a palindrome number, the reverse number could be overflow, so there will be "mirror != cache".


  • -1
    S

    here is my c code, beats 100% submissions

    bool isPalindrome(int x) {
            int lenx;
    	int rem;
    	int left, right;
    	int i, j;
    
    	if (x < 0)
    	{
    		return false;
    	}
    
    	/* get length of x */
    	rem = x;
    	lenx = 0;
    	while (rem)
    	{
    		lenx++;
    		rem /= 10;
    	}
    
    	i = 1;
    	j = lenx - 1;
    	left = x;
    	right = x;
            /* compare digit */
    	while (i <= j)
    	{
    		int tmp1 = (int)pow(10, j);
    		if (left / tmp1 != right % 10)
    		{
    			return false;
    		}
    		left %= tmp1;
    		right /= 10;
    		i++;
    		j--;
    	}
    
    	return true;
    }
    

Log in to reply
 

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