how to reverse number in javascript 1

how to reverse number in javascript

// Function to reverse Number
function reverseNum(n) {
  let r = n.toString().split('').reverse().join('');
  return Math.sign(n) * parseInt(r);
}

// Call
reverseNum(-267);
reverseNum(31522);

// Outputs
-762
22513

Here is what the above code is Doing:
1. First, we convert the number to a string using the toString() method.
2. Then, we split the string into an array of characters using the split() method.
3. Next, we reverse the array using the reverse() method.
4. Finally, we join the array back into a string using the join() method.
5. We then convert the string back to a number using the parseInt() method.
6. Finally, we return the number.

Similar Posts