7 Reverse Integer

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

  • If the integer's last digit is 0, what should the output be? i.e., cases such as 10, 100.
  • Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
  • For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
  • Try to implement without using string.

Notes before solution!
DETAILS!

  • Deal with negative number!
  • Note the smart way to only use an integer to record the reversing result.
while ( x != 0 ) {
  res_x += res_x *10 + x%10;
  x = x/10;
}
  • Overflow!
    INT_MAX = 2147483647, INT_MIN = -2147483648
    The reverse of a valid number might overflow! Note the trick to check overflow. (Avoid overflow number on both sides!)
    (INT_MAX - x%10)/10 < rev_x
    

Solution

class Solution {
public:
    int reverse(int x) {
        int rev_x = 0;
        int factor = 1;
        if ( x < 0 ) {
            factor = -1;
            x = -x;
        }
        while ( x != 0 ) {
            // note the way to check overflow!
            if ( (INT_MAX - x%10)/10 < rev_x ) return 0;
            rev_x = rev_x * 10 + x%10;
            x = (x-x%10)/10;
        }
        return factor*rev_x;
    }
};

results matching ""

    No results matching ""