[leetcode #537] Complex Number Multiplication

Seongyeol Shin·2021년 8월 24일
0

leetcode

목록 보기
18/196

Problem

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].
· i² == -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.

Constraints:

· num1 and num2 are valid complex numbers.

Idea

아무런 생각없이 String을 잘 분해하면 풀 수 있는 문제다. split을 잘 활용하면 간단하게 정수 부분과 허수 부분을 분해할 수 있을 것 같은데, 단순하게 '+'와 'i'의 index를 찾아 분해하였다.

알고리즘

  1. 첫 번째 수를 +와 i index를 사용해 정수 부분과 허수 부분을 구한다.
  2. 두 번째 수를 +와 i index를 사용해 정수 부분과 허수 부분을 구한다.
  3. 구해진 두 수를 곱하여 결과값을 리턴한다.

Solution

class Solution {
    public String complexNumberMultiply(String num1, String num2) {
    	int firstPlusIndex = num1.indexOf('+');
        int firstReal = Integer.parseInt(num1.substring(0,firstPlusIndex));
        int firstImaginaryIndex = num1.indexOf('i');
	int firstImaginary = Integer.parseInt(num1.substring(firstPlusIndex+1, firstImaginaryIndex));
    	int secondPlusIndex = num2.indexOf('+');
        int secondReal = Integer.parseInt(num2.substring(0,secondPlusIndex));
        int secondImaginaryIndex = num2.indexOf('i');
        int secondImaginary = Integer.parseInt(num2.substring(secondPlusIndex+1, secondImaginaryIndex));

	int resReal = firstReal * secondReal - firstImaginary * secondImaginary;
    	int resImaginary = firstReal * secondImaginary + firstImaginary * secondReal;

        return String.format("%d+%di", resReal, resImaginary);
    }
}

Reference

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

profile
서버개발자 토모입니다

0개의 댓글