Accepted c++ solution

  • 0

    class Solution {


    bool isPalindrome(int x)  {
        if (x < 0) return false;
        int result = 0;
        int oldx = x;
        while(x > 0){
            int a = x % 10;
            x = x/10;
            if ((INT_MAX - a)/10 < result) return false;
            result = result * 10 + a;
        if (result == oldx)
           return true;
        return false;


  • 0

    To explain the solution a little bit:

    if ((INT_MAX - a)/10 < result) return false;

    Actually we can rewrite it to

    if (INT_MAX < result*10+a) return false;

    Now it is pretty clear that this statement is to check if the result, after update, will overflow. However, if we write this statement as INT_MAX < result*10+a, result*10+a may overflow, since no int can be larger than INT_MAX. Thus, in order to avoid overflow in the if-statement, we need to change the order to INT_MAX - a)/10 < result. Other parts of the code is self-explaining.

  • 0

    I think it will be better if there is an if statement checking for x=0 since the answer will be true

  • 0

    yeah, you are right.

Log in to reply

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