Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Checking for special numbers in JavaScript
In JavaScript, checking for special numbers often involves mathematical operations on digits. A palindrome digit sum check determines if the sum of a number's digits forms a palindrome.
Problem
We need to write a JavaScript function that takes a number and returns true if the sum of its digits is a palindrome number, false otherwise.
For example, with input 781296:
const num = 781296;
The expected output is:
true
Output Explanation
The digit sum of 781296 is 7+8+1+2+9+6 = 33, which reads the same forwards and backwards (palindrome).
Solution Approach
Our solution involves two steps:
- Calculate the sum of all digits in the number
- Check if this sum is a palindrome
Example
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));
true
How It Works
The findSum function recursively extracts digits using modulo (%) and division operations. The palindromeDigitSum function converts the sum to a string, reverses it, and compares with the original sum.
Alternative Approach
Here's a more concise version using modern JavaScript methods:
const isPalindromeDigitSum = (num) => {
// Calculate digit sum
const digitSum = String(num)
.split('')
.reduce((sum, digit) => sum + parseInt(digit), 0);
// Check if sum is palindrome
const sumStr = String(digitSum);
return sumStr === sumStr.split('').reverse().join('');
};
console.log(isPalindromeDigitSum(781296)); // true
console.log(isPalindromeDigitSum(123)); // false (digit sum = 6)
console.log(isPalindromeDigitSum(191)); // true (digit sum = 11)
true false true
Key Points
- Palindromes read the same forwards and backwards
- Single-digit sums are always palindromes
- The recursive approach efficiently calculates digit sums
- String manipulation provides an easy palindrome check
Conclusion
Checking palindrome digit sums combines mathematical digit extraction with string palindrome validation. Both recursive and iterative approaches work effectively for this special number detection.
