Site Search:

Reverse an integer

Answer

Given an integer, return its reverse.
For example, given 123, the answer should be 321
given -123, the answer should be -321.



Solution

The problem test basic knowledge about Integers, there are a few test points.

1. the routing for pop the least significant digit from an integer:
int lsd = x%10;
x = x/10;
2. the routing of adding a least significant digit to an integer;
x = x*10 + lsd;
3.  x * 10 + lsd could overflow or underflow.
For positive x, If x * 10 + lsd > Integer.MAX_VALUE overflow will happen, when x == Integer.MAX_VALUE/10, lsd can not be bigger than 7.
For negative x, if x * 10 + lsd < Integer.MIN_VALUE underflow will happen, when x == Integer.MIN_VALUE/10, lsd can not be less than -8.

class ReverseNumber {
  public static void main(String...args) {
    System.out.println(getReverseNum(123));
  }
  //123
  public static int getReverseNum(int x) {
    int rev = 0;
    while(x > 0) {
      int pop = x%10;
      x = x/10;
      //check overflow
      if(x > Integer.MAX_VALUE/10 || (x == Integer.MAX_VALUE/10 && pop > 7)) return Integer.MAX_VALUE;
      if(x < Integer.MIN_VALUE/10 || (x == Integer.MIN_VALUE/10 && pop < -8)) return Integer.MIN_VALUE;
      rev = rev * 10 + pop;
    }
    return rev;
  }
}

The time cost is proportional to the number of digits, which is O(logn), where n is the integer, we take the logarithm of 10 to get the number of digits. The space cost is O(1)