- 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
Reverse digits of an integer in JavaScript without using array or string methods
We are required to write Number.prototype.reverse() function that returns the reversed number of the number it is used with.
For example −
234.reverse() = 432; 6564.reverse() = 4656;
Let’s write the code for this function. We will use a recursive approach like this −
Example
const reverse = function(temp = Math.abs(this), reversed = 0, isNegative = this < 0){ if(temp){ return reverse(Math.floor(temp/10), (reversed*10)+temp%10,isNegative); }; return !isNegative ? reversed : reversed*-1; }; Number.prototype.reverse = reverse; const n = -12763; const num = 43435; console.log(num.reverse()); console.log(n.reverse());
Output
The output in the console will be −
53434 -36721
Advertisements