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

1 7 9 + 2 8 4 4 6 3 1 1 Carries: 2 9+4=13 (carry 1) 7+8+1=16 (carry 1) 1+2+1=4 (no carry)

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:

  1. Extract the rightmost digits using modulo 10
  2. Add them with any existing carry
  3. If sum > 9, increment carry counter and set carry = 1
  4. Remove processed digits using integer division by 10
  5. 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.

Updated on: 2026-03-15T23:19:00+05:30

408 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements