KatInterview

Sum Two Arbitrarily Large Signed Integers as Strings

StringsAuto-graded · 26 test cases
EasyAuto-gradedStringsstring-manipulationmathdigit-arithmetic

Last 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 digit 0-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.