Skip to content

Commit cf7fb0f

Browse files
committed
[LeetCode Sync] Runtime - 5 ms (58.18%), Memory - 18.1 MB (53.58%)
1 parent 8f8108f commit cf7fb0f

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
<p>Given two non-negative integers, <code>num1</code> and <code>num2</code> represented as string, return <em>the sum of</em> <code>num1</code> <em>and</em> <code>num2</code> <em>as a string</em>.</p>
2+
3+
<p>You must solve the problem without using any built-in library for handling large integers (such as <code>BigInteger</code>). You must also not convert the inputs to integers directly.</p>
4+
5+
<p>&nbsp;</p>
6+
<p><strong class="example">Example 1:</strong></p>
7+
8+
<pre>
9+
<strong>Input:</strong> num1 = &quot;11&quot;, num2 = &quot;123&quot;
10+
<strong>Output:</strong> &quot;134&quot;
11+
</pre>
12+
13+
<p><strong class="example">Example 2:</strong></p>
14+
15+
<pre>
16+
<strong>Input:</strong> num1 = &quot;456&quot;, num2 = &quot;77&quot;
17+
<strong>Output:</strong> &quot;533&quot;
18+
</pre>
19+
20+
<p><strong class="example">Example 3:</strong></p>
21+
22+
<pre>
23+
<strong>Input:</strong> num1 = &quot;0&quot;, num2 = &quot;0&quot;
24+
<strong>Output:</strong> &quot;0&quot;
25+
</pre>
26+
27+
<p>&nbsp;</p>
28+
<p><strong>Constraints:</strong></p>
29+
30+
<ul>
31+
<li><code>1 &lt;= num1.length, num2.length &lt;= 10<sup>4</sup></code></li>
32+
<li><code>num1</code> and <code>num2</code> consist of only digits.</li>
33+
<li><code>num1</code> and <code>num2</code> don&#39;t have any leading zeros except for the zero itself.</li>
34+
</ul>
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
class Solution:
2+
def addStrings(self, num1: str, num2: str) -> str:
3+
i, j = len(num1) - 1, len(num2) - 1
4+
result = []
5+
carry = 0
6+
while i >= 0 or j >= 0 or carry:
7+
val1 = 0 if i < 0 else (ord(num1[i]) - ord("0"))
8+
val2 = 0 if j < 0 else (ord(num2[j]) - ord("0"))
9+
carry, val = divmod(val1 + val2 + carry, 10)
10+
result.append(str(val))
11+
i, j = i - 1, j - 1
12+
return "".join(result[::-1])
13+

0 commit comments

Comments
 (0)