Adding Large Numbers Using Strings in Go

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 Go function 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 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.

Step 1 - Initializing Variables

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 ints, i and j, to point to the current digit in num1 and num2, respectively. We'll also need a carry int variable to hold the carryovers from each addition operation. Lastly, we'll use a slice of bytes, named result, to store our resultant number, where each digit from the addition is appended to the front.

Go
func addLargeNumbers(num1, num2 string) string {
    i := len(num1) - 1
    j := len(num2) - 1
    carry := 0
    var result []byte

We prefer using a slice of bytes over strings.Builder because a slice of bytes allows for efficient insertion of each computed digit at the front, aligning with our right-to-left processing, while strings.Builder only allows appending at the end of the string. This, in turn, simplifies the logic by avoiding the need for additional steps such as reversing the result at the end.

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