Emmanuel Akinfulubi

JavaScriptMath

Reverse an integer's digits in JavaScript

Intermediate · 4 min read

Reversing a number's digits turns 12345 into 54321. It is a classic warm-up, and it is also the building block for checking whether a number is a palindrome, which is the next exercise.

In this tutorial you will write reverseDigits(n) using only arithmetic, then a shorter version with strings. Both keep a minus sign in front, so -123 becomes -321. Then you will look at two ways reversing loses information: trailing zeros, and a 17-digit number that is already wrong before your function runs. You need to know while loops and the % operator.

Building a number digit by digit

You already know how to take digits off the right end of a number: n % 10 gives the last digit, and Math.floor(n / 10) removes it. To build a number up, you do the opposite: multiply what you have by 10 to make room, then add the new digit.

JavaScript

let out = 0;
out = out * 10 + 5; // 5
out = out * 10 + 4; // 54
out = out * 10 + 3;
console.log(out); // 543

Taking digits off one number and adding them onto another, in that order, reverses it.

Math.sign

Math.sign(n) gives -1 for a negative number, 1 for a positive one and 0 for zero. It lets you put the minus sign aside, work with the positive number, and put the sign back at the end.

Here is the exercise. Try it yourself first if you like, then read on and we will build it together.

43 Reversing the digits of a number

fair

Turn 12345 into 54321, keeping any minus sign in front. Then show two ways the operation loses information: with a trailing zero, and with a 17-digit input.

Stuck? Three hints, smallest first
  1. 1. Arithmetically: result = result * 10 + n % 10, then floor-divide n by 10.
  2. 2. By string: split, reverse, join, and convert back — remembering the sign is a character.
  3. 3. A 17-digit literal is already rounded before your function is called.

Step 1: reverse a positive number

Step 1

function reverseDigits(n) {
  let rest = n;
  let out = 0;
  while (rest > 0) {
    out = out * 10 + (rest % 10);
    rest = Math.floor(rest / 10);
  }
  return out;
}
console.log(reverseDigits(12345)); // 54321

Each pass moves one digit from the end of rest to the end of out. When rest reaches 0 there are no digits left.

Now try a negative number:

JavaScript

console.log(reverseDigits(-123)); // 0

The loop condition rest > 0 is false from the start, so nothing happens and you get 0.

Step 2: keep the sign

Step 2

function reverseDigits(n) {
  const sign = Math.sign(n);
  let rest = Math.abs(n);
  let out = 0;
  while (rest > 0) {
    out = out * 10 + (rest % 10);
    rest = Math.floor(rest / 10);
  }
  return sign * out;
}
console.log(reverseDigits(-123)); // -321
console.log(reverseDigits(0));    // 0
console.log(reverseDigits(7));    // 7

We save the sign, reverse the positive version with Math.abs, and multiply the sign back in. This is the answer's version.

Step 3: the string version

With strings, you split the number into characters, reverse the list and join it back up. The trap is the minus sign: it is a character too.

JavaScript

console.log(Number(String(-123).split('').reverse().join(''))); // NaN

Reversed, '-123' becomes '321-', which isn't a number. So the string version also sets the sign aside first:

Step 3

const reverseByString = (n) =>
  Math.sign(n) * Number(String(Math.abs(n)).split('').reverse().join(''));
console.log(reverseByString(12345)); // 54321
console.log(reverseByString(-123));  // -321

Step 4: trailing zeros disappear

Step 4

console.log(reverseDigits(1200));                // 21
console.log(reverseDigits(reverseDigits(1200))); // 12

1200 reversed is "0021", and a number can't keep leading zeros, so it is 21. Reverse 21 and you get 12, not 1200. 12 and 1200 both reverse to 21, so there is no way back. That isn't a bug in your code: the operation itself throws the zeros away. If you need to undo a reversal, keep the digit count separately, or keep the digits as a string.

Step 5: a 17-digit number

Step 5

const big = 12345678901234567;
console.log(big);               // 12345678901234568
console.log(reverseDigits(big)); // 86543210987654320

The last digit of big changed from 7 to 8 before reverseDigits was even called. JavaScript numbers hold whole numbers exactly only up to Number.MAX_SAFE_INTEGER, which is 9007199254740991 (16 digits). A 17-digit literal past that is rounded to the nearest number JavaScript can store, as soon as the code is read. The function then correctly reverses the wrong input.

The largest safe number still reverses fine:

JavaScript

console.log(reverseDigits(Number.MAX_SAFE_INTEGER)); // 1990474529917009

For digits beyond the safe range, keep them in a string or use BigInt from the start.

The full solution

The answer panel has the arithmetic and string versions, then prints 12345, the 1200 round trip, -123, the 17-digit literal and its reversal, and the reversal of Number.MAX_SAFE_INTEGER. Press Run to see the output.

The answer

function reverseDigits(n) {
  const sign = Math.sign(n);
  let rest = Math.abs(n);
  let out = 0;
  while (rest > 0) {
    out = out * 10 + (rest % 10);
    rest = Math.floor(rest / 10);
  }
  return sign * out;
}

const reverseByString = (n) =>
  Math.sign(n) * Number(String(Math.abs(n)).split('').reverse().join(''));

const big = 12345678901234567;          // 17 digits, and already not what it says

console.log('12345 ->', reverseDigits(12345));
console.log('1200  ->', reverseDigits(1200), '<- the zeros are gone for good');
console.log('back  ->', reverseDigits(reverseDigits(1200)));
console.log('-123  ->', reverseDigits(-123));
console.log('the 17-digit literal:', big);
console.log('reversed            :', reverseDigits(big));
console.log('MAX_SAFE reversed   :', reverseDigits(Number.MAX_SAFE_INTEGER));

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('12345 reverses to 54321, both ways', [reverseDigits(12345), reverseByString(12345)], [54321, 54321]);
test('the sign stays in front', reverseDigits(-123), -321);
test('0 reverses to 0, and a single digit to itself', [reverseDigits(0), reverseDigits(7)], [0, 7]);
test('trailing zeros vanish: 1200 becomes 21', reverseDigits(1200), 21);
test('so reversing twice does not return the original', reverseDigits(reverseDigits(1200)), 12);
test('a palindrome is the fixed point of this operation', [121, 1221, 9].every((n) => reverseDigits(n) === n), true);
test('the 17-digit literal was rounded before the call', big, 12345678901234568);
test('so its reversal starts from the rounded value', reverseDigits(big), 86543210987654320);
test('MAX_SAFE_INTEGER reverses within range, and exactly', [reverseDigits(Number.MAX_SAFE_INTEGER), Number.isSafeInteger(reverseDigits(Number.MAX_SAFE_INTEGER))], [1990474529917009, true]);

Reversal is not invertible, and the reason is not floating point: 1200 and 12 both reverse to 21, so information is destroyed by the operation itself. Any code that reverses, transforms, then reverses back has to keep the digit count separately.

The 17-digit case is a different failure and worth separating carefully. 12345678901234567 is not a safe integer, so the literal becomes 12345678901234568 at parse time — before reverseDigits runs. The function is correct; its input was already wrong. Assert on the literal itself, as above, and the cause is unmistakable. Past 2**53, digits belong in a string or a BigInt.

Common mistakes

  • Forgetting the sign. The arithmetic loop returns 0 for negatives, and the string version returns NaN. Set the sign aside with Math.sign and Math.abs.
  • Expecting a round trip. 1200 reversed twice is 12. The trailing zeros are gone after the first reversal.
  • Blaming the function for big inputs. A 17-digit literal is rounded before your code runs. Check the input itself with Number.isSafeInteger.

Try it yourself

  1. Write reverseKeepingZeros(n) that returns a string, so 1200 gives '0021'.
  2. Find a number below 100 whose reversal is the same number. How many are there?
  3. Use reverseDigits to find the sum of 47 and its reversal, then repeat with the result. How many steps until you get a palindrome?

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.