有帮助吗?

Checking whether the sum of digits of a number forms a Palindrome Number or not in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in a number, sums its digits and checks whether that sum is a Palindrome number or not. The function should return true if the sum is Palindrome, false otherwise.

For example, if the number is 697,

Then the sum of its digit will be 22, which indeed, is a Palindrome number. Therefore, our function should return true for 697.

Example

Following is the code −

const num = 697;
const sumDigit = (num, sum = 0) => {
   if(num){
      return sumDigit(Math.floor(num / 10), sum + (num % 10));
   };
   return sum;
};
const isPalindrome = num => {
   const revered = +String(num)
   .split("")
   .reverse()
   .join("");
   return revered === num;
};
const isSumPalindrome = num => isPalindrome(sumDigit(num));
console.log(isSumPalindrome(num));

Output

This will produce the following output in console −

true
raja
Published on 30-Sep-2020 17:46:06
Advertisements
有帮助吗?
不隶属于 Tutorialspoint
scroll top