Lesson 4
Adding Large Numbers Using Strings in Java
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, in which 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 Java method that adds these two "string-numbers" together. The challenge is to perform the addition without converting these entire strings into integers.

At the end, your method 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 an int variable named carry to hold the carryovers from each addition operation. Lastly, we'll use an ArrayList<Character> named result to store our resultant number, where each digit from the addition is appended 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.

Java
1public class LargeNumberAdder { 2 public static String addLargeNumbers(String num1, String num2) { 3 int i = num1.length() - 1; 4 int j = num2.length() - 1; 5 int carry = 0; 6 ArrayList<Character> result; 7 result = new ArrayList<>();
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.

Java
1public class LargeNumberAdder { 2 public static String addLargeNumbers(String num1, String num2) { 3 int i = num1.length() - 1; 4 int j = num2.length() - 1; 5 int carry = 0; 6 ArrayList<Character> result = new ArrayList<>(); 7 8 while(i >= 0 || j >= 0 || carry != 0) { 9 int n1 = (i >= 0) ? num1.charAt(i) - '0' : 0; 10 int n2 = (j >= 0) ? num2.charAt(j) - '0' : 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. Finally, we reverse result and join the digits together to obtain our result.

Java
1import java.util.ArrayList; 2import java.util.Collections; 3 4public class LargeNumberAdder { 5 public static String addLargeNumbers(String num1, String num2) { 6 int i = num1.length() - 1; 7 int j = num2.length() - 1; 8 int carry = 0; 9 ArrayList<Character> result = new ArrayList<>(); 10 11 while(i >= 0 || j >= 0 || carry != 0) { 12 int n1 = (i >= 0) ? num1.charAt(i) - '0' : 0; 13 int n2 = (j >= 0) ? num2.charAt(j) - '0' : 0; 14 int current = n1 + n2 + carry; 15 carry = current / 10; 16 current = current % 10; 17 result.add((char) ('0' + current)); 18 i--; 19 j--; 20 } 21 22 Collections.reverse(result); 23 StringBuilder resultString = new StringBuilder(result.size()); 24 for (Character c : result) { 25 resultString.append(c); 26 } 27 return resultString.toString(); 28 } 29 30 public static void main(String[] args) { 31 System.out.println(addLargeNumbers("1454178195297", "8458263917502")); 32 // Outputs 9912442112799 33 } 34}
Lesson Summary

Congratulations! You have successfully implemented a method 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.