Reverse Integer

Reverse digits of an integer.

Example1:

x = 123, return 321

Example2:

x = -123, return -321

def reverse(x: Int): Int = {
  var _x = x
  var result = 0
  while (_x != 0) {
    result = result * 10 + _x % 10
    _x /= 10
  }
  if (result <= Int.MaxValue && result >= Int.MinValue) result else 0
}

reverse(123)
reverse(-123)
reverse(Int.MinValue)
reverse(Int.MaxValue)

Last updated