44ms c++ solution


  • 13
    Z

    You can also view more solution on Github

    class Solution {
    public:
    	bool isPalindrome(int x) {
    		if (x < 0) return false;
    		int p1 = 0, p2 = x;
    		while (p2 > 0) {
    			p1 = p1*10 + p2%10;
    			p2 /= 10;
    		}
    		return p1 == x;
    	}
    };

  • 0
    C

    Great solution..but can you explain me how the overflow condition is handled in your code?


  • 0
    B

    calculate the reversed number and compare with the origin number.


  • 0
    S

    The question stats 'do not use extra space'. Your solution does not meet this restriction while using p1 to store the temporary result.


  • 2
    C

    If the reversed number overflow, the number is not a palindromic! So this code works.


  • 0
    E

    class Solution {
    public:
    bool isPalindrome(int x) {
    if(x<0|| (x!=0 &&x%10==0)) return false;
    int sum=0;
    while(x>sum)
    {
    sum = sum*10+x%10;
    x = x/10;
    }
    return (x==sum)||(x==sum/10);
    }
    };

    why this solution takes 80ms? what is the difference from yours?


  • 0
    A

    I had the same question. Not sure why it's a longer time.


  • 0
    E

    I also had the same solution, but my run time is 128 ms; and I don't think it could be faster than the most voted answer.


  • 0
    Z

    The same question with me. And I test this solution just now, which shows 76ms.
    And I test another solution just the same as this one but some small difference in the final block that are if(a==num) return true; else return false; This one runs for 88ms...


Log in to reply
 

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