Add Strings — LeetCode 415 Python Solution
- Problem
- #415
- Pattern
- Math and Number Theory
- Reading time
- 5 min
- Source
- leetcode.com
The problem
Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string. You must solve the problem without using any built-in library for handling large integers (such as BigInteger).
Example
- Input
- num1 = "11", num2 = "123"
- Output
- "134"
Python solution
class Solution:
def addStrings(self, num1: str, num2: str) -> str:
i, j = len(num1) - 1, len(num2) - 1
ans = []
c = 0
while i >= 0 or j >= 0 or c:
a = 0 if i < 0 else int(num1[i])
b = 0 if j < 0 else int(num2[j])
c, v = divmod(a + b + c, 10)
ans.append(str(v))
i, j = i - 1, j - 1
return "".join(ans[::-1])
def subStrings(self, num1: str, num2: str) -> str:
m, n = len(num1), len(num2)
neg = m < n or (m == n and num1 < num2)
if neg:
num1, num2 = num2, num1
i, j = len(num1) - 1, len(num2) - 1
ans = []
c = 0
while i >= 0:
c = int(num1[i]) - c - (0 if j < 0 else int(num2[j]))
ans.append(str((c + 10) % 10))
c = 1 if c < 0 else 0
i, j = i - 1, j - 1
while len(ans) > 1 and ans[-1] == '0':
ans.pop()
if neg:
ans.append('-')
return ''.join(ans[::-1])Complexity
| Measure | Complexity |
|---|---|
| Time | O(\max(m, n)), where m and n are the lengths of the two strings respectively |
| Space | O(1) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 415. Add Strings is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 415. Add Strings?
- LeetCode 415. Add Strings is rated Easy on LeetCode.
- What is the time complexity of LeetCode 415. Add Strings?
- The Python solution on this page runs in O(\max(m, n)), where m and n are the lengths of the two strings respectively.
- What is the space complexity of LeetCode 415. Add Strings?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 415. Add Strings cover?
- LeetCode 415. Add Strings is tagged Math, String and Simulation on LeetCode.