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
Selected Reading
Negative number digit sum in JavaScript
We are required to write a JavaScript function that takes in a negative integer and returns the sum of its digits.
Example Input
For example: If the number is:
-5456
Expected Output
Then the output should be:
5+4+5+6 = 20
Using String Manipulation and Reduce
The following approach converts the number to string, splits it into digits, and uses reduce to sum them:
const num = -5456;
const sumNum = num => {
return String(num).split("").reduce((acc, val, ind) => {
if(ind === 0){
return acc;
}
if(ind === 1){
acc -= +val;
return acc;
};
acc += +val;
return acc;
}, 0);
};
console.log(sumNum(num));
20
Simpler Approach Using Math.abs()
A cleaner solution uses Math.abs() to remove the negative sign and then sum the digits:
const digitSum = (num) => {
return Math.abs(num)
.toString()
.split('')
.reduce((sum, digit) => sum + parseInt(digit), 0);
};
console.log(digitSum(-5456)); // 20
console.log(digitSum(-123)); // 6
console.log(digitSum(-999)); // 27
20 6 27
Using While Loop
An alternative mathematical approach without string conversion:
const digitSumLoop = (num) => {
num = Math.abs(num); // Remove negative sign
let sum = 0;
while (num > 0) {
sum += num % 10; // Get last digit
num = Math.floor(num / 10); // Remove last digit
}
return sum;
};
console.log(digitSumLoop(-5456)); // 20
console.log(digitSumLoop(-789)); // 24
20 24
Comparison
| Method | Readability | Performance |
|---|---|---|
| String + Reduce (Complex) | Low | Slower |
| Math.abs() + String | High | Good |
| While Loop | Medium | Fastest |
Conclusion
Use Math.abs() with string methods for simplicity and readability. The while loop approach is most efficient for performance-critical applications.
Advertisements
