Short accepted c++ solution using int without long or string


  • 6
    T
     int reverse(int x) {
            if(INT_MIN == x) return 0;
            if(x < 0) return -reverse(-x);
            int result = 0;
            while(x > 0){
                int a = x % 10;
                x = x / 10;
                if((INT_MAX - a) / 10 < result)
                  return 0;
                result = result * 10 + a;
            }
            return result;
        }

  • 1
    T

    python version:

    def reverse(self, x):
            if x < 0: return -self.reverse(-x);
            result = 0;
            while x > 0:
                result = result * 10 + x % 10;
                x = x / 10;
            return 0 if result > 0x7FFFFFFF else result

  • 0
    K

    I am not sure why I changed if((INT_MAX - a)/10 < result) to if((result*10 + a) > INT_MAX), that would come to failure cases. Any idea?


  • 0
    T

    Because (result*10 + a) has been overflow


Log in to reply
 

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