Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Checking for Special Numbers 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 true if the sum of the digits of the number num is a palindrome number, false otherwise.

For example, if the input to the function is −

const num = 781296;

Then the output should be −

const output = true;

Output Explanation

Because the digit sum of 781296 is 33 which is a palindrome number.

Example

Following is the code −

 Live Demo

const num = 781296;

const findSum = (num, sum = 0) => {
if(num){
return findSum(Math.floor(num / 10), sum + (num % 10));

};
return sum;

};

const palindromeDigitSum = (num = 1) => {

const sum = findSum(num);
const str = String(sum);
const arr = str.split('');
const reversed = arr.reverse();
const revNum = +arr.join('');

return revNum === sum;
};

console.log(palindromeDigitSum(num));

Output

Following is the console output−

true
Updated on: 2021-04-21T11:39:20+05:30

430 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements