Reverse Integer

LeetCode Q 7 - Reverse Integer

Given a 32-bit signed integer, reverse digits of an integer.
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Solution

Algorithm:
The tricky is we need to identify if the overflow issue would happen at every conversion.
if (res < Integer.MIN_VALUE / 10 || res > Integer.MAX_VALUE / 10)
Note: res * 10 < Integer.MIN_VALUE doesn’t work, because if res is overflow, then res will be transformed before multiplication.

Code:

public int reverse(int x) {	
  if (x == 0 || x > Integer.MAX_VALUE || x < Integer.MIN_VALUE) return 0;

  int res = 0;
  while (x != 0) {
    if (res < Integer.MIN_VALUE / 10 || res > Integer.MAX_VALUE / 10)
      return 0;

    res = res * 10 + x % 10;
    x /= 10;
  }

  return res;
}

   Reprint policy


《Reverse Integer》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC