Leetcode 415. Add Strings

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Add Strings

2. Solution

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution:
def addStrings(self, num1: str, num2: str) -> str:
result = ''
length1 = len(num1)
length2 = len(num2)

if length1 < length2:
num1, num2 = num2, num1
length1, length2 = length2, length1

flag = 0
for i in range(-1, -length2 - 1, -1):
temp = int(num1[i]) + int(num2[i]) + flag
flag = 1 if temp > 9 else 0
result = str(temp % 10) + result
for i in range(-length2 - 1, -length1 - 1, -1):
temp = int(num1[i]) + flag
flag = 1 if temp > 9 else 0
result = str(temp % 10) + result
if flag:
result = str(flag) + result
return result

Reference

  1. https://leetcode.com/problems/add-strings/
如果有收获,可以请我喝杯咖啡!