KatInterview

Sum Two Large Numbers Represented as Digit Strings

StringsAuto-graded · 22 test cases
MediumAuto-gradedStringsstring-manipulationmathsimulation

Last updated

Tests manual digit-by-digit addition with carry propagation on arbitrarily large integers stored as strings.

Write a function that computes the sum of two non-negative integers represented as strings of decimal digits. Return the result as a string.

The integers may be extremely large—up to 10,000 digits each—far exceeding the capacity of standard integer types. You must implement the addition logic manually by processing individual digits. You may not convert an entire input string to a built-in numeric type, and you may not use external big-integer libraries.

Function Signature

def sum_large_numbers(a: str, b: str) -> str:

Rules

  • Each string consists solely of digit characters ('0' through '9').
  • Neither input has unnecessary leading zeros, with the exception that the value zero is represented as "0".
  • The two strings may differ in length.
  • Your output must be a valid decimal representation with no leading zeros. The only exception is when the sum is zero, which should be returned as "0".

Constraints

  • 1 <= len(a) <= 10^4
  • 1 <= len(b) <= 10^4
  • Each character in a and b is a digit from '0' to '9'.

Examples

Example 1

Input: sum_large_numbers('11', '123')

Output: '134'

Example 2

Input: sum_large_numbers('999', '1')

Output: '1000'

Example 3

Input: sum_large_numbers('0', '0')

Output: '0'

Hints

Hint 1

Process digits from right to left, just like manual addition on paper, keeping track of the carry at each position.

Hint 2

Handle strings of different lengths by using separate indices for each input, treating exhausted positions as contributing zero.

Hint 3

Don't forget to handle the final carry after both strings are fully processed—it may add an extra leading digit to the result.