알고리즘 문제 풀이

[LeetCode] 537. Complex Number Multiplication

_OB1N 2021. 8. 25. 11:57

문제 출처: https://leetcode.com/problems/complex-number-multiplication/

 

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


문제

복소수는 "real+imaginaryi" 형태의 문자열로 표현될 수 있다:

  • real 은 실수 부분이고, [-100, 100]의 범위를 갖는 정수이다.
  • imaginary 는 허수 부분이고 [-100, 100]의 범위를 갖는 정수이다.
  • i2 == -1.

두 복소수 문자열 num1과 num2가 주어지면, 두 값을 곱한 결과를 복수수 문자열로 반환하라.

예제

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.
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.

풀이

문자열 데이터를 다루는 방법을 알고 있는지 물어보는 문제로 해석되는데, 그 이유는 다음과 같다.

 

두 복소수를 곱을 하여 얻어야 하는 복소수의 문자열의 구성은 다음과 같이 표현할 수 있다:

  • real = (num1_real * num2_real) - (num1_imaginary * num2_imaginary)
  • imaginary = (num1_real * num2_imaginary) + (num2_real * num1_imaginary) 

그렇기 때문에, 결국 주어지는 num1 과 num2 에서 실수 부분과 허수 부분을 분리하는 것이 이 문제의 핵심이다.

 

문자열에서 실수와 허수를 분리하는 다양한 방법이 있을 수 있다. 간단한 예로, 주어지는 문자열에서 "+"의 위치를 찾고 찾아진 위치의 앞은 실수로 취급하고, 뒤는 허수로 취급하는 방법이 있을 수 있다.

 

여기에서는 정규표현식을 이용하여 실수와 허수를 구분하고자 한다. 정규표현식을 이용하고자 하는 이유는 주어지는 복소수 문자열에는 일정한 패턴("숫자+숫자i")이 존재하기 때문이다. 다음 코드는 정규표현식을 이용하여 실수와 허수를 추출하는 코드이다.

var findRealAndImaginary = funtion(num) {
    const reg = /(-?\d+)\+(-?\d+)i/g;
    const result = reg.exec(num);
    return [parseInt(result[1]), parseInt(result[2)];
}

이 findRealAndInaginary() 함수를 이용하여 두 복소수의 곱을 구하는 코드는 다음과 같이 작성할 수 있다.

var complexMultiply = function(num1, num2) {
    const [num1Real, num1Imagi] = findRealAndImaginary(num1);
    const [num2Real, num2Imagi] = findRealAndImaginary(num2);
    
    const multiplyReal = (num1Real * num2Real) - (num1Imagi * num2Imagi);
    const multiplyImagi = (num1Real * num2Imagi) + (num2Real * num1Imagi);
    
    return `${multiplyReal}+${multiplyImagi}i`;
}

 

Github: 537.js

 

GitHub - opwe37/Algorithm-Study

Contribute to opwe37/Algorithm-Study development by creating an account on GitHub.

github.com

 

댓글수0