๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Algorithm/Leetcode

[Leetcode] Complex Number Multiplication (#537)

 

 

๋ฌธ์ œ 

 

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ํ•œ ๊ฒƒ์€ +๊ฐ€ ์—†์–ด๋„ ๊ธฐ๋ณธ์ ์œผ๋กœ ๊ฐ ๊ณ„์ˆ˜๋Š” ์ •์ˆ˜ํ˜•ํƒœ๋ฅผ ๋„๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. 

 

 

 

 

Complex Number Multiplication - 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

 

'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