Reverse a number in JavaScript
Beginner · 3 min read
Reversing the digits of a number, so 32243 becomes 34223, is a favorite beginner exercise and a common interview warm-up. It also turns up in real puzzles: checking whether a number reads the same both ways, or building check digits. In this tutorial you will do it two ways, once with text and once with plain arithmetic, and then check that they agree.
You will write reverseNumber(n) and reverseByMaths(n). Both take a whole number, positive or negative, and return the reversed number. You need to know what a function and a while loop are. Everything else is explained as we go.
Numbers and text
JavaScript treats 1234 (a number) and '1234' (text, also called a string) as different things. Strings have tools for reversing; numbers don't. So one way to reverse a number is: turn it into text, reverse the text, turn it back.
console.log(String(1234)); // 1234, now as text
console.log(Number('4321')); // 4321, now as a number
Leading zeros don't exist
What is 1200 reversed? The digits backwards are 0021. But as a number, 0021 is just 21, so the answer is 21. That is not a bug. Numbers simply have no leading zeros. If you need to keep them, you want a string, and that is a different function.
Here is the exercise. Try it on your own first if you like, then read on.
13 Reverse a number
easyTake a whole number and produce it with its digits reversed. Handle negatives sensibly.
Stuck? Three hints, smallest first
- 1. Turning it into text, reversing, and turning it back is the readable way.
- 2. A negative sign needs handling separately, or it ends up at the wrong end.
- 3. Reversing a number ending in zero loses that zero, because
021is just21. That is arithmetic, not a bug.
Step 1: the text way
Splitting a string with split('') gives an array of its characters. Arrays have a reverse() method, and join('') glues the characters back together.
function reverseNumber(n) {
const digits = String(n).split('').reverse().join('');
return Number(digits);
}
console.log(reverseNumber(32243)); // 34223
console.log(reverseNumber(1200)); // 21
Each method hands its result to the next one. That is called chaining.
Step 2: the minus sign
Now try a negative number:
console.log(reverseNumber(-1234)); // NaN
The text '-1234' reversed is '4321-'. The minus sign ended up at the wrong end, and Number('4321-') is NaN (Not a Number).
The fix is to remember the sign, reverse the digits without it, and put the sign back. Math.abs gives the number without its sign.
function reverseNumber(n) {
const sign = n < 0 ? -1 : 1;
const digits = String(Math.abs(n)).split('').reverse().join('');
return sign * Number(digits);
}
console.log(reverseNumber(-1234)); // -4321
console.log(reverseNumber(7)); // 7
sign is -1 for a negative number and 1 otherwise. Multiplying by it puts the minus back when needed.
Step 3: the arithmetic way
You can also reverse a number without turning it into text. Two operators do the work:
n % 10gives the last digit.1234 % 10is4.Math.floor(n / 10)drops the last digit.Math.floor(1234 / 10)is123.
Take the last digit off one number and add it to the end of another, over and over. "Add to the end" means multiply by 10 and add the digit.
function reverseByMaths(n) {
const sign = n < 0 ? -1 : 1;
let left = Math.abs(n);
let out = 0;
while (left > 0) {
out = out * 10 + (left % 10);
left = Math.floor(left / 10);
}
return sign * out;
}
console.log(reverseByMaths(1234)); // 4321
Here is how out and left change for 1234:
left 1234 out 0
left 123 out 4
left 12 out 43
left 1 out 432
left 0 out 4321
The loop stops when nothing is left. For 0 the loop never runs, and the answer is 0.
Step 4: check that they agree
Two different methods that give the same answers on many inputs are good evidence that both are right.
for (const n of [32243, -1234, 1200, 7, 0]) {
console.log(n, '->', reverseNumber(n), '| by maths:', reverseByMaths(n));
}
Every line shows the same answer twice. 1200 gives 21 both ways.
The full solution
The complete answer has both functions and prints them side by side for five numbers, including a negative, a number ending in zeros, a single digit and zero. Press Run to see the output.
function reverseNumber(n) {
const sign = n < 0 ? -1 : 1;
const digits = String(Math.abs(n)).split('').reverse().join('');
return sign * Number(digits);
}
// The arithmetic version, with no text conversion at all.
function reverseByMaths(n) {
const sign = n < 0 ? -1 : 1;
let left = Math.abs(n);
let out = 0;
while (left > 0) {
out = out * 10 + (left % 10);
left = Math.floor(left / 10);
}
return sign * out;
}
for (const n of [32243, -1234, 1200, 7, 0]) {
console.log(n, '->', reverseNumber(n), '| by maths:', reverseByMaths(n));
}
Output
7 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 7 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a plain number', reverseNumber(32243), 34223);
test('a negative keeps its sign', reverseNumber(-1234), -4321);
test('trailing zeros vanish, correctly', reverseNumber(1200), 21);
test('a single digit is itself', reverseNumber(7), 7);
test('zero is zero', reverseNumber(0), 0);
test('both methods agree', reverseByMaths(32243), reverseNumber(32243));
test('and agree on negatives', reverseByMaths(-1234), reverseNumber(-1234));
1200 reversing to 21 rather than 0021 is correct: leading zeros do not exist in a number. If you needed them kept, the answer is text, not a number, and that is a different function. The two implementations are shown because they agree on every case, which is a stronger check than either one alone.
Common mistakes
- Reversing the minus sign along with the digits.
'-1234'becomes'4321-', which isNaN. Take the sign off first. - Expecting 1200 to give 0021. A number can't have leading zeros. Return a string if you need them.
- Using
left / 10withoutMath.floor.leftbecomes a decimal (123.4, 12.34 and so on), so it shrinks slowly instead of reaching 0. For 1234 the loop runs 327 times and returnsInfinity.
Try it yourself
- Write
isNumberPalindrome(n)that returnstruewhen a number reads the same both ways, like 12321. - Write
reverseDigitsAsText(n)that keeps the zeros, so 1200 gives'0021'. - Use the arithmetic method to add up the digits of a number instead of reversing them.