Reversing negative and positive numbers in JavaScript

Problem

We are required to write a JavaScript function that takes in a number and returns its reversed number.

One thing that we should keep in mind is that numbers should preserve their sign; i.e., a negative number should still be negative when reversed.

Example

Following is the code ?

const num = -224;
function reverseNumber(n) {
    let x = Math.abs(n)
    let y = 0
    while (x > 0) {
        y = y * 10 + (x % 10)
        x = Math.floor(x / 10)
    };
    return Math.sign(n) * y
};
console.log(reverseNumber(num));
-422

How It Works

The algorithm works by extracting digits from right to left and building the reversed number:

  1. Math.abs(n) removes the sign to work with positive digits
  2. The while loop extracts the last digit using x % 10
  3. It builds the reversed number by multiplying the current result by 10 and adding the extracted digit
  4. Math.sign(n) preserves the original sign in the final result

Additional Examples

console.log(reverseNumber(123));    // Positive number
console.log(reverseNumber(-456));   // Negative number
console.log(reverseNumber(1000));   // Number with trailing zeros
console.log(reverseNumber(0));      // Zero
321
-654
1
0

Alternative Approach Using String Conversion

function reverseNumberString(n) {
    const sign = Math.sign(n);
    const reversed = parseInt(Math.abs(n).toString().split('').reverse().join(''));
    return sign * reversed;
}

console.log(reverseNumberString(-224));
console.log(reverseNumberString(567));
-422
765

Conclusion

Both mathematical and string-based approaches work effectively for reversing numbers while preserving their sign. The mathematical approach is more efficient, while the string approach is more readable.

Updated on: 2026-03-15T23:19:00+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements