Reverse Integer

medium math

Problem

Given a 32-bit signed integer x, reverse its digits. If reversing causes the value to overflow signed 32-bit range, return 0.

Inputx = 123
Output321
Peel digits 3, 2, 1 from x; push onto result.

def reverse(x):
    sign = -1 if x < 0 else 1
    x = abs(x)
    res = 0
    while x:
        res = res * 10 + x % 10
        x //= 10
    res *= sign
    if res < -2**31 or res > 2**31 - 1:
        return 0
    return res
function reverse(x) {
  const sign = x < 0 ? -1 : 1;
  x = Math.abs(x);
  let res = 0;
  while (x) {
    res = res * 10 + x % 10;
    x = Math.floor(x / 10);
  }
  res *= sign;
  if (res < -(2 ** 31) || res > (2 ** 31) - 1) return 0;
  return res;
}
class Solution {
    public int reverse(int x) {
        long res = 0;
        int sign = x < 0 ? -1 : 1;
        x = Math.abs(x);
        while (x != 0) {
            res = res * 10 + x % 10;
            x /= 10;
        }
        res *= sign;
        if (res < Integer.MIN_VALUE || res > Integer.MAX_VALUE) return 0;
        return (int) res;
    }
}
int reverse(int x) {
    long long res = 0;
    int sign = x < 0 ? -1 : 1;
    long long y = llabs((long long)x);
    while (y) {
        res = res * 10 + y % 10;
        y /= 10;
    }
    res *= sign;
    if (res < INT_MIN || res > INT_MAX) return 0;
    return (int) res;
}
Time: O(log|x|) Space: O(1)