DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 47

The task is to implement a string addition function with all non-negative integers in string.

The boilerplate code:

function add(num1, num2) {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

The addition begins by starting from the end of both strings

let i = num1.length - 1
let j = num.length - 1
Enter fullscreen mode Exit fullscreen mode

When 2 numbers are added, and the result is greater than 10, the first number is carried over to the next number pair

let carry = 0
Enter fullscreen mode Exit fullscreen mode

While there are digits left to be added or numbers that are carried, the addition operation continues

 while(i >= 0 || j >= 0 || carry > 0) {
    const digit1 = i >= 0 ? Number(num1[i--]) : 0;
    const digit2 = j >= 0 ? Number(num2[j--]) : 0;
    const sum = digit1 + digit2 + carry;
  }
Enter fullscreen mode Exit fullscreen mode

The result for each addition will be the remainder after the first number is carried

result = (sum % 10) + result;
Enter fullscreen mode Exit fullscreen mode

The value of the number carried

carry = Math.floor(sum / 10)
Enter fullscreen mode Exit fullscreen mode

The final code:

function add(num1, num2) {
  // your code here
  let i = num1.length - 1;
  let j = num2.length - 1;
  let carry = 0;
  let result = '';

  while(i >= 0 || j >= 0 || carry > 0) {
    const digit1 = i >= 0 ? Number(num1[i--]) : 0;
    const digit2 = j >= 0 ? Number(num2[j--]) : 0;
    const sum = digit1 + digit2 + carry;

    result = (sum % 10) + result;
    carry = Math.floor(sum / 10)
  }
  return result;
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)