forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
36 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
# Time: O(n) | ||
# Space: O(1) | ||
|
||
# Given two non-negative numbers num1 and num2 represented as string, | ||
# return the sum of num1 and num2. | ||
# | ||
# Note: | ||
# | ||
# The length of both num1 and num2 is < 5100. | ||
# Both num1 and num2 contains only digits 0-9. | ||
# Both num1 and num2 does not contain any leading zero. | ||
# You must not use any built-in BigInteger library or | ||
# convert the inputs to integer directly. | ||
|
||
class Solution(object): | ||
def addStrings(self, num1, num2): | ||
""" | ||
:type num1: str | ||
:type num2: str | ||
:rtype: str | ||
""" | ||
result = [] | ||
i, j, carry = len(num1) - 1, len(num2) - 1, 0 | ||
|
||
while i >= 0 or j >= 0 or carry: | ||
if i >= 0: | ||
carry += ord(num1[i]) - ord('0'); | ||
i -= 1 | ||
if j >= 0: | ||
carry += ord(num2[j]) - ord('0'); | ||
j -= 1 | ||
result.append(str(carry % 10)) | ||
carry /= 10 | ||
result.reverse() | ||
|
||
return "".join(result) |