KatInterview

Sum Two Large Numbers Represented as Strings

StringsAuto-graded · 19 test cases
HardAuto-gradedStringsstringsmath-bitssimulation

Last updated

Tests whether a candidate can implement column-by-column addition with carry logic on digit strings, without converting the whole string to a native integer.

Problem Statement

You are given two non-negative integers, each stored as a string of decimal digits. Return their sum, also as a string.

There is one restriction: you may not convert an entire input string into a Python integer (so int(num1) + int(num2) is off limits). You must perform the addition yourself, one digit at a time.

How to approach it

Think of how you would add two numbers on paper: align the rightmost digits, add one column at a time from right to left, record the ones digit of each column, and carry the tens digit into the next column.

Constraints

  • 1 <= len(num1), len(num2) <= 10,000
  • Both strings contain only the characters '0' through '9'.
  • Neither string has leading zeros, except for the single-character string "0".
  • The returned string must also have no leading zeros (except for the result "0" itself).

Examples

Example 1

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

Output: '134'

Example 2

Input: sum_digit_strings('456', '77')

Output: '533'

Example 3

Input: sum_digit_strings('0', '0')

Output: '0'

Hints

Hint 1

Work from right to left using two index pointers, one for each string. When a pointer goes out of bounds, treat that string as contributing 0 to the current column.

Hint 2

Maintain a carry variable that starts at 0. Each column produces a digit equal to (digit_a + digit_b + carry) % 10 and a new carry equal to (digit_a + digit_b + carry) // 10. The carry can never exceed 1.

Hint 3

Keep the loop running while either pointer is still in range OR the carry is non-zero — this handles the overflow case where the result has more digits than either input (e.g. '99' + '1' = '100'). Collect digits into a list and reverse once at the end instead of prepending on every step.