Lesson 4
Adding Extremely Large Numbers in JavaScript
Introduction

Hello and welcome! Today, we'll delve deep into a captivating problem involving large numbers — specifically, adding extraordinarily large numbers. As you may have noticed, traditional calculators and even some programming languages struggle when dealing with excessively large numbers. To handle such scenarios efficiently, we'll simulate this process manually using strings. By the end of this discussion, you'll be able to add together numbers that have thousands or even tens of thousands of digits. Intriguing, right? Let's get started!

Task Statement

In today's task, we'll venture into the realm of large numbers, where we are given two exceedingly large positive integers. However, these aren't your average, everyday large numbers. They are so enormous they're represented as strings that can be up to 10,000 digits long!

Your mission, should you choose to accept it, is to write a JavaScript function that adds these two "string-numbers" together. The challenge is to perform the addition without converting these entire strings into integers.

In the end, your function should return the resulting sum, represented as a string. At first glance, this might seem daunting, but don't worry — we'll break it down step by step, emulating the way we manually add numbers.

Solution Building: Step 1

Before we dive into the code, let's first discuss the strategy we're going to follow. Remember that every digit in a number carries value, and the position of the digit determines its influence on the total value of the number. This system is known as place-value notation.

The first step involves initializing our variables. We'll use two integers, i and j, to point to the current digit in num1 and num2, respectively. We'll also need a variable named carry to hold the carryovers from each addition operation. Lastly, we'll use an Array named result to store our resultant number, where each digit from the addition is intended to be pushed to the front.

We start iterating from the end (rightmost side) of each string because the rightmost digit is the least significant digit, and this is where we begin when performing manual addition. Processing the least significant digits first allows us to handle carryover operations easily and propagate any necessary changes to the more significant digits on the left.

JavaScript
1function addLargeNumbers(num1, num2) { 2 let i = num1.length - 1; 3 let j = num2.length - 1; 4 let carry = 0; 5 let result = [];
Solution Building: Step 2

After initializing our variables, it's time to move on to the next step. Here, we'll scan through num1 and num2 from right to left, moving from the least significant digit to the most significant one.

For each iteration, we extract the digits n1 from num1 and n2 from num2. If i or j is less than 0, that means we've processed all the digits in one of the numbers. Therefore, we treat any additional digits as 0. Additionally, the condition carry !== 0 in the while loop ensures that we continue processing even if we have finished all the digits in both numbers but still have a remaining carry. This is important because the carry represents an additional digit when the sum of the last digits exceeds 9.

JavaScript
1function addLargeNumbers(num1, num2) { 2 let i = num1.length - 1; 3 let j = num2.length - 1; 4 let carry = 0; 5 let result = []; 6 7 while (i >= 0 || j >= 0 || carry !== 0) { 8 let n1 = (i >= 0) ? parseInt(num1.charAt(i)) : 0; 9 let n2 = (j >= 0) ? parseInt(num2.charAt(j)) : 0;

Here, we use the ternary operator to ensure that if i or j is less than 0, we treat any additional digits as 0. The ternary operator works with a condition followed by a question mark (?), then the true expression, a colon (:), and the false expression. For example, (i >= 0) ? parseInt(num1.charAt(i)) : 0 means if i is greater than or equal to 0, we take the digit at index i from num1; otherwise, we use 0.

Solution Building: Step 3

After obtaining digits n1 and n2, our next step is to add them. This addition also includes the carry, which accumulates any overflow from the addition of previous column digits. This sum results in a one- or two-digit number, where the "tens" place becomes a new carry and the "units" place is the result digit.

Subsequently, we add current to the result array and decrement both i and j before starting the next iteration. Since we are appending digits instead of pushing them to the front, we will reverse result at the end and join the digits together to obtain our final result.

JavaScript
1function addLargeNumbers(num1, num2) { 2 let i = num1.length - 1; 3 let j = num2.length - 1; 4 let carry = 0; 5 let result = []; 6 7 while (i >= 0 || j >= 0 || carry !== 0) { 8 let n1 = (i >= 0) ? parseInt(num1.charAt(i)) : 0; 9 let n2 = (j >= 0) ? parseInt(num2.charAt(j)) : 0; 10 let current = n1 + n2 + carry; 11 carry = Math.floor(current / 10); 12 current = current % 10; 13 result.push(current); 14 i--; 15 j--; 16 } 17 18 result.reverse(); 19 return result.join(''); 20} 21 22// Example usage: 23console.log(addLargeNumbers("1454178195297", "8458263917502")); 24// Outputs 9912442112799
Lesson Summary

Congratulations! You have successfully implemented a function to add very large numbers by mimicking the way we traditionally perform addition operations. Achieving this not only requires a robust understanding of place-value notation but also the ability to manipulate strings and arrays effectively. This task was likely challenging, but remember, every struggle leads to greater accomplishment. Now, with this powerful tool in your arsenal, you can confidently tackle problems involving large numbers. In the upcoming practice session, you can test your new skills with a range of similar challenges. Enjoy coding, and remember, learning is a journey, so take pleasure in the ride!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.