 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
 