Adding Extremely Large Numbers Using Strings in C#

Introduction

Hello and welcome! Today, we'll delve deep into a captivating problem that involves large numbers — specifically, adding extraordinarily large numbers. As you may have noticed, traditional calculators and even some programming languages struggle when numbers get exceedingly large. 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 step into the world of large numbers, focusing specifically on two exceedingly large positive integers. However, these aren't your average, everyday large numbers. They are so vast they're represented as strings that can be up to 10,000 digits long!

Accepting our mission means writing a C# method that combines these two "string-numbers" together. The challenge is to perform the addition without converting the entire strings into integers.

Finally, our method should return the resulting sum, represented as a string. While it might seem daunting at first, don't worry — we'll break it down step by step, mimicking how we manually add numbers.

Solution Building: Step 1

Before we start coding, let's consider the strategy we're going to adopt. You may recall that each digit in a number has a value, and the position of the digit determines its influence on the total value of the number. This system is called place-value notation.

The first step requires the initialization of our variables. We'll use two indices, i and j, to point to the current digit in num1 and num2, respectively. We'll also need an integer carry to hold carryovers from each addition operation. Lastly, we'll employ a List<char> named res to hold our result, where each digit from the addition is appended at the front.

using System;
using System.Collections.Generic;

class Program
{
    static string AddLargeNumbers(string num1, string num2)
    {
        int i = num1.Length - 1, j = num2.Length - 1, carry = 0;
        List<char> res = new List<char>();
    }
}

Solution Building: Step 2

Having initialized our variables, we can advance to the next step, which involves scanning through num1 and num2 from right to left. This scanning goes 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 below 0, we've processed all the digits in one of the numbers. Consequently, we consider these additional digits as 0.

        while (i >= 0 || j >= 0 || carry > 0)
        {
            int n1 = i >= 0 ? num1[i] - '0' : 0;
            int n2 = j >= 0 ? num2[j] - '0' : 0;
        }
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal