43. 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 or convert the inputs to integer directly.
제한 사항
- 1 <= num1.length, num2.length <= 200
- num1 and num2 consist of digits only.
- Both num1 and num2 do not contain any leading zero, except the number 0 itself.
입출력 예
Example 1:
Input: num1 = "2", num2 = "3"
Output: "6"
Example 2:
Input: num1 = "123", num2 = "456"
Output: "56088"
Python 코드
Python code
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))
* 참고 링크 : https://wellsw.tistory.com/94?category=1054641
C++ 코드
C ++ code
class Solution {
public:
string multiply(string num1, string num2) {
string res(num1.size() + num2.size(), '0');
for (int i = num1.size() - 1; i >= 0; --i) {
int carry = 0;
for (int j = num2.size() - 1; j >= 0; --j) {
int tmp = (res[i + j + 1] - '0') + (num2[j] - '0')*(num1[i] - '0') + carry;
res[i + j + 1] = tmp % 10 + '0';
carry = tmp/10;
}
res[i] += carry;
}
auto pos = res.find_first_not_of('0');
if (pos == string::npos)
return "0";
return res.substr(pos, res.length() - pos);
}
};
* 참고 링크 : https://blog.fearcat.in/a?ID=00850-66ef66e8-11ca-463c-82ae-c4af5cb77fae
출처
'코딩테스트 > Leet Code' 카테고리의 다른 글
[Leet Code] 225. Implement Stack using Queues (0) | 2022.01.21 |
---|---|
[Leet Code] 150. Evaluate Reverse Polish Notation (0) | 2022.01.21 |
[Leet Code] 27. Remove Element (0) | 2022.01.14 |
[Leet Code] 20. Valid Parentheses (0) | 2022.01.14 |
[Leet Code] 234. Palindrome Linked List (0) | 2022.01.14 |