Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Counting steps to make number palindrome in JavaScript
Problem
We are required to write a JavaScript function that takes in a number, num, as the first and the only argument.
Our function should return the number of special steps needed to obtain a palindrome. The special step is: "reverse the digits, and add to the original number". If the resulting number is not a palindrome, repeat the procedure with the sum until the resulting number is a palindrome.
For example, if the input to the function is −
Input
const num = 87;
Output
const output = 4;
Output Explanation
Because the steps involved are −
87 + 78 = 165; 165 + 561 = 726; 726 + 627 = 1353; 1353 + 3531 = 4884
Example
Following is the code −
const num = 87;
const countSteps = (num) => {
let res = 0;
while (!isPalindrome(num)) {
res++
num += +('' + num).split``.reverse().join``
};
return res;
}
const isPalindrome = num => {
let i = 0
let str = '' + num
while (i++ <= str.length / 2) {
if (str[i] !== str[str.length - 1 - i]) return false
};
return true
}
console.log(countSteps(num));
Output
4
Advertisements