๋ฌธ์
A complex number can be represented as a string on the form "real+imaginaryi" where:
- real is the real part and is an integer in the range [-100, 100].
- imaginary is the imaginary part and is an integer in the range [-100, 100].
- i2 == -1.
Given two complex numbers num1 and num2 as strings, return a string of the complex number that represents their multiplications.
Example 1:
Input: num1 = "1+1i", num2 = "1+1i"
Output: "0+2i"
Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i.
Example 2:
Input: num1 = "1+-1i", num2 = "1+-1i"
Output: "0+-2i"
Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i.
ํด์ค ์ฝ๋
class Solution(object):
def complexNumberMultiply(self, a, b):
# Split numbers to real and imagine parts without "i".
ra, ia = a[:-1].split("+")
rb, ib = b[:-1].split("+")
# Convert all parts to integer.
ra, rb = int(ra), int(rb)
ia, ib = int(ia),int(ib)
# Return result with formula of multiply for complex numbers.
return "{}+{}i".format((ra*rb)-(ia*ib),(ra*ib)+(ia*rb))
๋ถ์ > ์ด ๋ฌธ์ ์ ์ ๊ทผํ์ง ๋ชปํ๋ ๊ฒ์ ์ด๋ป๊ฒ ๋ฌธ์์ด์ ์์์ผ๋ก ๋ง๋ค์ด์ผ ํ ์ง ๊ฐ์ ์ก์ง ๋ชปํ๊ธฐ ๋๋ฌธ์ด๋ค. ์ด ์ฝ๋๋ ์ฐ์ ๋ณต์์์ ์ ์ ๋ถ๋ถ๊ณผ ๋ณต์์๊ฐ ์๋ ์ ์ ๋ถ๋ถ์ ๋ถ๋ฆฌํ์ฌ ๊ณ์๋ง ๋ฐ๋ก ์ ์ฅํ์ฌ ์์์ ๊ณ์ฐํ ํ์ ๋ฌธ์์ด ํ์์ผ๋ก ๋ง๋ค์ด์ค์ผ๋ก์จ ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ์๋ค. ๊ณ์๋ง์ ๋ฐ๋ก ๋ถ๋ฆฌํ ๋๋ ๋ณต์์ i ๋ ๋ฌด์กฐ๊ฑด ๋ฌธ์์ด์ ๊ฐ์ฅ ๋์ ์์นํ๋ฏ๋ก [:-1]์ ์ด์ฉํ์ฌ ๋ง์ง๋ง ๋ฌธ์ i๋ฅผ ์ ์ธํ๊ณ ๋ฌธ์์ด์ ์ฌ๋ผ์ด์ฑ ํด์ฃผ์๊ณ +๋ฅผ ๊ธฐ์ค์ผ๋ก ๋ฌธ์์ด์ splitํ ๊ฒ์ +๊ฐ ์์ด๋ ๊ธฐ๋ณธ์ ์ผ๋ก ๊ฐ ๊ณ์๋ ์ ์ํํ๋ฅผ ๋๊ธฐ ๋๋ฌธ์ด๋ค.
'Algorithm > Leetcode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Leetcode] Print Words Vertically (#1324) (0) | 2022.04.20 |
---|---|
[Leetcode] Reshape the Matrix (#566) (0) | 2022.04.20 |
[Leetcode] Game of Life (#289) (0) | 2022.04.19 |
[Leetcode] Transpose Matrix (#867) (0) | 2022.04.18 |
[Leetcode] Last Stone Weight (#1046) (0) | 2022.04.08 |