알고리즘/LeetCode
LeetCode 풀기 - 43. Multiply Strings
앤테바
2021. 11. 10. 20:55
반응형
43. Multiply Strings
https://leetcode.com/problems/multiply-strings/
Multiply Strings - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
문제)
솔루션1)
Built-in BigInteger library를 사용하지 말아햐 하는 조건이 있다.
string을 number로 바꾸는 함수를 만들어야한다.
class Solution:
def multiply(self, num1: str, num2: str) -> str:
num_mapping = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4,
'5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
def str_to_int(num_str):
num = 0
for i, c in enumerate(num_str[::-1]):
num += pow(10, i) * num_mapping[c]
return num
return str(str_to_int(num1) * str_to_int(num2))
솔루션2)
솔루션1)에서 char to num 변환하는 것을 hash를 사용했는데 ord() 함수를 이용하게 변경했다
class Solution:
def multiply(self, num1: str, num2: str) -> str:
def str_to_int(num_str):
num = 0
for i, c in enumerate(num_str[::-1]):
num += pow(10, i) * (ord(c) - ord('0'))
return num
return str(str_to_int(num1) * str_to_int(num2))
반응형