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: 21-Apr-2021

309 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements