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
Number of carries required while adding two numbers in JavaScript
When adding two numbers on paper, we sometimes need to "carry" a digit to the next column when the sum of digits exceeds 9. This article shows how to count the total number of carries required during addition.
Problem
We need to write a JavaScript function that takes two numbers and counts how many carries are needed when adding them digit by digit, just like manual addition on paper.
For example, when adding 179 and 284:
- 9 + 4 = 13 (carry 1)
- 7 + 8 + 1 = 16 (carry 1)
- 1 + 2 + 1 = 4 (no carry)
Total carries: 2
Solution
const num1 = 179;
const num2 = 284;
const countCarries = (num1 = 1, num2 = 1) => {
let res = 0;
let carry = 0;
while (num1 + num2) {
// Check if sum of current digits plus carry exceeds 9
carry = +(num1 % 10 + num2 % 10 + carry > 9);
res += carry;
// Move to next digits (remove rightmost digit)
num1 = Math.floor(num1 / 10);
num2 = Math.floor(num2 / 10);
}
return res;
};
console.log(countCarries(num1, num2));
2
How It Works
The algorithm processes digits from right to left:
- Extract the rightmost digits using modulo 10
- Add them with any existing carry
- If sum > 9, increment carry counter and set carry = 1
- Remove processed digits using integer division by 10
- Repeat until no digits remain
Additional Examples
console.log(countCarries(123, 456)); // No carries console.log(countCarries(999, 1)); // 3 carries console.log(countCarries(99, 99)); // 2 carries
0 3 2
Conclusion
This function efficiently counts carries by processing digits right-to-left and tracking when digit sums exceed 9. It's useful for understanding addition algorithms and implementing custom arithmetic operations.
Advertisements
