[LeetCode]Complex Number Mutiplication

2024. 4. 5. 16:06·SW개발/코딩테스트

https://leetcode.com/problems/complex-number-multiplication/description/

 

LeetCode - The World's Leading Online Programming Learning Platform

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

 

문제 분석

real + imaginary i로 이루어진 두개의 숫자를 곱한 결과를 출력하는 문제입니다. 허수의 제곱은 -1로 간주합니다.

 

처음 시도한 답안

class Solution:
    def complexNumberMultiply(self, num1: str, num2: str) -> str:
        real_num1, imaginary_num1 = num1.split("+")
        imaginary_num1 = imaginary_num1.split("i")[0]
        nums1 = [int(real_num1), int(imaginary_num1)]

        real_num2, imaginary_num2 = num2.split("+")
        imaginary_num2 = imaginary_num2.split("i")[0]
        nums2 = [int(real_num2), int(imaginary_num2)]

        a, b, c, d = 1, 1, 1, 1

        a = a * nums1[0] * nums2[0]
        b = b * nums1[0] * nums2[1]
        c = c * nums1[1] * nums2[0]
        d = d * nums1[1] * nums2[1]

        a = a + (d*-1) # for i^2

        answer = str(a)+"+"+str(b+c)+"i"

        return answer

접근 방법

  1. (a+bi)와 (c+di)의 곱셈을 하는 방식으로 풀이 했습니다.
  2. 먼저 + 구분자를 통해 실수와 허수 부분을 나눕니다.
  3. 허수 부분의 경우는 곱셈 연산을 하기 위해 i를 제거합니다.
  4. a, b, c, d의 계수는 곱셉을 위해 전부 1로 설정합니다.
  5. 곱셈의 결과인 ac, adi, bci, bdi^2가 되도록 계수끼리 곱셉을 수행합니다.
  6. i^2 = -1이므로 a항과의 덧셈을 위해 a + (d*-1)로 처리합니다.
  7. 형식에 맞게 출력하면 곱셉한 결과를 구할 수 있습니다.

a, b, c, d라는 계수를 가지고 곱셉하듯이 풀이하면 되는 문제입니다.

 

728x90

'SW개발 > 코딩테스트' 카테고리의 다른 글

[LeetCode]Number of Islands  (0) 2024.04.07
[LeetCode]Clumsy Factorial  (0) 2024.04.06
[LeetCode]Diagonal Traverse  (0) 2024.04.04
[LeetCode]Game of Life  (0) 2024.04.03
[LeetCode]Add Binary  (0) 2024.04.02
'SW개발/코딩테스트' 카테고리의 다른 글
  • [LeetCode]Number of Islands
  • [LeetCode]Clumsy Factorial
  • [LeetCode]Diagonal Traverse
  • [LeetCode]Game of Life
Leffe_pt
Leffe_pt
개발자로서 성장하면서 배워온 지식과 경험을 공유하는 공간입니다.
  • Leffe_pt
    Leffe's tistory
    Leffe_pt
  • 전체
    오늘
    어제
    • 분류 전체보기 (307)
      • SW개발 (303)
        • 코딩테스트 (172)
        • 개발이야기 (23)
        • IT 용어 (17)
        • Python (22)
        • Django (46)
        • Flask (2)
        • Database (1)
        • SQLAlchemy (0)
        • Javascript (5)
        • Linux, Unix (3)
        • JAVA (2)
        • Spring (10)
      • 회고 (4)
      • 사진 (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    django
    트리 #AVL #알고리즘 #자료구조
    배달비 공유
    g
    Contributor
    라이프 스타일
    배공파용
    플레이스토어
    오픈소스
    어플리케이션
    배달
    음식
    컨트리뷰터
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Leffe_pt
[LeetCode]Complex Number Mutiplication
상단으로

티스토리툴바