Reverse an Integer

Reverse an integer using math operations.

Build up a new number m by multiplying by 10 and dividing the original number n by 10 until n is 0. The digit in the ‘ones’ position is taken from the original and added to the new number at each iteration.

int reverse(int n) {
  int m = 0

  while (n) {
    int r = n % 10
    m = m * 10 + r
    n = n / 10
  }

  return m
}
Scroll to top