LeetCode 筆記 - 43. Multiply Strings

題目在此 43. Multiply Strings

給兩個字串型態的數字,請計算出相乘的值,並回傳其字串型態

解題思維

直接用 int() 太無聊了,嘗試自己寫寫看如何把字串轉換成數字吧 ☺️

程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution:
def multiply(self, num1: str, num2: str) -> str:

table = {
'0': 0,
'1': 1,
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9
}

def convertStoI(s):
base = 1

result = 0
for c in reversed(s):
result += table[c] * base
base *= 10

return result

value1 = convertStoI(num1)
value2 = convertStoI(num2)

return str(value1 * value2)

相關文章