- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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));
Output
-422
Advertisements