Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
31 |
Tags
- 리트코드
- 문자열
- 미디움
- recursive
- 재귀
- easy
- backtracking
- sorting
- Array
- binary search
- hash table
- tree
- two pointers
- math
- matrix
- Binary
- string
- Medium
- HashTable
- leetcode
- 중간
- 쉬움
- Python
- list
- linked list
- Depth-first Search
- 이진트리
- DP
- binary tree
- dfs
Archives
- Today
- Total
부부의 코딩 성장 일기
LeetCode 43(Multiply Strings, Python) 본문
1. 문제 링크
Multiply Strings - LeetCode
Can you solve this real interview question? Multiply Strings - Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string. Note: You must not use any built-in BigInteger library
leetcode.com
2. 문제 설명
- num1과 num2 가 str으로 주어졌을 때 이 두 수를 곱한 결과를 str으로 반환
- built-in BigInteger 라이브러리를 사용하거나 직접 int로 변환하면 안됨.
- 내가 built-in BigInteger 라이브러리를 사용한 것인지 아닌 지 잘 모르겠음.
3. 처음 풀이
- dict에 ‘1’:1 처럼 str:int를 딕셔너리에 넣고
- 문자열을 순회하며 딕셔너리에서 해당되는 val을 가져오며 10배씩하며 더하면 type을 int로 바꿀 수 있음.
- 이후 곱셈을 한 후 str으로 변환하여 반환
- 문제에서 원하는 풀이가 이게 맞는 지 모르겠다.
class Solution:
def multiply(self, num1: str, num2: str) -> str:
str_to_int = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}
num1_int = 0
num2_int = 0
for i in num1:
num1_int = 10*num1_int + str_to_int[i]
for i in num2:
num2_int = 10*num2_int + str_to_int[i]
return str(num1_int * num2_int)
4. 다른 풀이
- ord 이용, ord('2')-ord('0') 계산하면 2가 나옴.
class Solution:
def multiply(self, num1: str, num2: str) -> str:
o = ord('0')
d1 = 0
for n in num1:
d1 *= 10
d1 += ord(n) - o
d2 = 0
for n in num2:
d2 *= 10
d2 += ord(n) - o
return str(d1*d2)
5. 배운 점
- ord와 chr, ord는 문자열을 받아 해당 유니코드를 반환, chr은 유니코드를 받아 해당 문자를 반환
- ord('a') = 97, chr(97)='a'
'Algorithm > LeetCode' 카테고리의 다른 글
LeetCode 46(Permutations, Python) (1) | 2024.01.03 |
---|---|
LeetCode 45(Jump Game II, Python) (0) | 2024.01.02 |
LeetCode 40(Combination Sum II, Python) (1) | 2023.12.31 |
LeetCode 39(Combination Sum , Python) (0) | 2023.12.30 |
LeetCode 38(Count and Say, Python) (2) | 2023.12.29 |