Sum Two Arbitrarily Large Signed Integers as Strings
StringsAuto-graded · 26 test casesLast updated
Tests digit-by-digit arithmetic with sign handling and carry/borrow logic for adding very large signed integers represented as strings.
Write a function that computes the sum of two signed integers given as strings. The integers may be too large to fit in standard numeric types, so you must work with the string representation directly without converting to int or long.
Each input string represents a signed decimal integer. It may optionally start with a + or - sign, followed by one or more digits. Leading zeros may be present.
Your function must return the sum as a string in canonical form: no leading + sign, no leading zeros (except for the value zero itself, which is "0"), and zero is never negative (never "-0").
Constraints
- Each input string is non-empty and well-formed: an optional
+or-followed by at least one digit0-9. - The length of each string is at most 10,000 characters.
- You may not use built-in arbitrary-precision conversion functions like
int()to parse the entire number.
Examples
Example 1
Input: sum_large_signed_ints('-123', '45')
Output: '-78'
Example 2
Input: sum_large_signed_ints('999', '1')
Output: '1000'
Example 3
Input: sum_large_signed_ints('-0', '+0')
Output: '0'
Example 4
Input: sum_large_signed_ints('+00123', '-00045')
Output: '78'
Hints
Hint 1
Separate each number into its sign and its magnitude (the absolute value as a digit string). This reduces the problem to addition or subtraction of non-negative magnitudes depending on whether the signs match.
Hint 2
When the signs are the same, add the magnitudes digit-by-digit from right to left, propagating any carry. When the signs differ, subtract the smaller magnitude from the larger and attach the sign of the operand with the larger magnitude.
Hint 3
Normalize inputs by stripping leading zeros and treating any zero value as positive. This ensures "-0" and "+0" both produce "0", and comparison logic works correctly.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Break each input into a sign and a magnitude (absolute value), then apply grade-school addition or subtraction based on whether the signs match.
First, parse each string to extract its sign (+1 or -1) and its magnitude (the digit sequence). Remove any leading zeros from the magnitudes, and treat zero as always positive to avoid -0 in the output.
When both signs are identical: add the two magnitudes digit by digit from right to left, tracking a carry. The result keeps the common sign (unless the result is zero, which is always unsigned).
When the signs differ: this is effectively subtraction. Compare the magnitudes to determine which is larger. Subtract the smaller from the larger using borrowing logic, and attach the sign of the operand with the larger magnitude. If the magnitudes are equal, return "0" immediately.
The magnitude comparison works without converting to integers: after stripping leading zeros, a longer string is larger; if lengths match, lexicographic comparison of digit strings gives the correct ordering since '0' through '9' are in numeric order.
Correctness
For any integers x and y with signs s₁ and s₂ and magnitudes |x| and |y|:
- If s₁ = s₂, then x + y = s₁ · (|x| + |y|).
- If s₁ ≠ s₂ and |x| > |y|, then x + y = s₁ · (|x| − |y|).
- If s₁ ≠ s₂ and |x| < |y|, then x + y = s₂ · (|y| − |x|).
- If s₁ ≠ s₂ and |x| = |y|, then x + y = 0.
Each case is handled explicitly. The digit arithmetic follows standard base-10 carry and borrow rules. Normalizing zero to positive sign before branching ensures that -0 + -0 cannot produce -0.
Complexity
Time: O(n + m), where n and m are the lengths of the input strings. Parsing, stripping zeros, comparison, and the add/subtract loops each scan the inputs at most once.
Space: O(max(n, m)) for the output and intermediate normalized strings. This is optimal since the result itself requires this space.
Solution
def sum_large_signed_ints(num1: str, num2: str) -> str:
def extract_sign(s):
if s[0] == '-':
return -1, s[1:]
if s[0] == '+':
return 1, s[1:]
return 1, s
def strip_leading_zeros(s):
s = s.lstrip('0')
return s or '0'
def compare_magnitudes(a, b):
a = strip_leading_zeros(a)
b = strip_leading_zeros(b)
if len(a) != len(b):
return 1 if len(a) > len(b) else -1
if a == b:
return 0
return 1 if a > b else -1
def add_digit_strings(a, b):
i = len(a) - 1
j = len(b) - 1
carry = 0
result = []
while i >= 0 or j >= 0 or carry:
total = carry
if i >= 0:
total += ord(a[i]) - ord('0')
i -= 1
if j >= 0:
total += ord(b[j]) - ord('0')
j -= 1
result.append(chr(ord('0') + total % 10))
carry = total // 10
return ''.join(reversed(result))
def subtract_digit_strings(a, b):
i = len(a) - 1
j = len(b) - 1
borrow = 0
result = []
while i >= 0:
digit = ord(a[i]) - ord('0') - borrow
if j >= 0:
digit -= ord(b[j]) - ord('0')
j -= 1
if digit < 0:
digit += 10
borrow = 1
else:
borrow = 0
result.append(chr(ord('0') + digit))
i -= 1
return strip_leading_zeros(''.join(reversed(result)))
sign1, mag1 = extract_sign(num1)
sign2, mag2 = extract_sign(num2)
mag1 = strip_leading_zeros(mag1)
mag2 = strip_leading_zeros(mag2)
if mag1 == '0':
sign1 = 1
if mag2 == '0':
sign2 = 1
if sign1 == sign2:
result = add_digit_strings(mag1, mag2)
return result if sign1 == 1 or result == '0' else '-' + result
cmp = compare_magnitudes(mag1, mag2)
if cmp == 0:
return '0'
if cmp > 0:
result = subtract_digit_strings(mag1, mag2)
return result if sign1 == 1 else '-' + result
result = subtract_digit_strings(mag2, mag1)
return result if sign2 == 1 else '-' + result