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
Digit sum upto a number of digits of a number in JavaScript
We are required to write a JavaScript function that takes in two numbers, let's say m and n as arguments.
n will always be smaller than or equal to the number of digits present in m. The function should calculate and return the sum of first n digits of m.
Problem Statement
If the input numbers are:
const m = 5465767; const n = 4;
Then the output should be:
20
because 5 + 4 + 6 + 5 = 20
Solution Using String Conversion
The most straightforward approach is to convert the number to a string and iterate through the first n characters:
const m = 5465767;
const n = 4;
const digitSumUpto = (m, n) => {
if(n > String(m).length){
return 0;
};
let sum = 0;
for(let i = 0; i < n; i++){
const el = +String(m)[i];
sum += el;
};
return sum;
};
console.log(digitSumUpto(m, n));
20
Alternative Solution Using Mathematical Approach
We can also solve this without string conversion by extracting digits mathematically:
const digitSumMath = (m, n) => {
const numStr = String(m);
if(n > numStr.length) return 0;
let sum = 0;
let temp = m;
const totalDigits = numStr.length;
// Extract digits from left to right
for(let i = 0; i < n; i++){
const divisor = Math.pow(10, totalDigits - i - 1);
const digit = Math.floor(temp / divisor);
sum += digit;
temp = temp % divisor;
}
return sum;
};
console.log(digitSumMath(5465767, 4)); // 20
console.log(digitSumMath(123456, 3)); // 6 (1+2+3)
20 6
How It Works
The string conversion method works by:
- Converting the number to a string to easily access individual digits
- Iterating through the first n characters
- Converting each character back to a number using the unary plus operator (+)
- Adding each digit to the running sum
Edge Cases
// Test edge cases console.log(digitSumUpto(123, 5)); // 0 (n > number of digits) console.log(digitSumUpto(987654, 0)); // 0 (no digits to sum) console.log(digitSumUpto(5, 1)); // 5 (single digit)
0 0 5
Conclusion
The string conversion approach is simpler and more readable for digit manipulation. Use this method when you need to sum the first n digits of any number efficiently.
