Mastering Large Number Addition with Strings

Introduction

Welcome! In this lesson, we’ll tackle a fascinating challenge: adding extraordinarily large numbers that exceed the capacity of typical numerical operations in programming languages. To achieve this in Ruby, we’ll simulate the process of addition manually by treating these numbers as strings.

By the end of this lesson, you’ll have a method to handle numbers with thousands, or even tens of thousands, of digits. Let’s dive in!

Task Statement

Our task involves working with two enormous positive integers represented as strings. Each string can be up to 10,000 digits long. The goal is to create a Ruby method to add these string-based numbers without converting them into integers. Instead, we’ll emulate manual addition step by step, much like solving math problems on paper.

The function should return the sum as a string. This approach ensures we can handle even the largest of numbers efficiently.

Solution Building: Step 1

To begin, we’ll reverse the strings representing the numbers. Why? Because addition starts from the least significant digit, and reversing makes it easy to iterate from the smallest place value to the largest.

We’ll also initialize variables:

  • max_length to track the length of the longer number.
  • carry to store any overflow from column addition.
  • result as an array to store each digit of the sum.

Here’s how it looks:

def add_large_numbers(num1, num2)
  # Reverse the strings to facilitate addition from least significant digit
  num1 = num1.reverse
  num2 = num2.reverse

  # Initialize variables
  max_length = [num1.length, num2.length].max
  carry = 0
  result = []

The above code initializes the preparation steps for manual addition using string manipulation.

Solution Building: Step 2

Next, we perform digit-by-digit addition. Using a loop, we’ll:

  • Extract the digit at position i from both numbers (or use 0 if a number is shorter).
  • Add these digits along with any carry.
  • Determine the new carry and the current digit to append to result.

Here’s the code:

  # Perform digit-by-digit addition
  max_length.times do |i|
    digit1 = i < num1.length ? num1[i].to_i : 0
    digit2 = i < num2.length ? num2[i].to_i : 0

    sum = digit1 + digit2 + carry
    carry = sum / 10
    result << (sum % 10)
  end

The above snippet undertakes the addition process for each digit, managing carry-over values.

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