0537. Complex Number Multiplication - kumaeki/LeetCode GitHub Wiki

0537. Complex Number Multiplication


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^2 == -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.

解法1

class Solution {
    public String complexNumberMultiply(String num1, String num2) {
        String[] arr1 = num1.split("\\+"); 
        Integer r1 = Integer.valueOf(arr1[0]);
        String i1str = arr1[1].substring(0, arr1[1].length() - 1);
        Integer i1 = i1str.charAt(0) == '-' ? -Integer.valueOf(i1str.substring(1)) : Integer.valueOf(i1str);
        
        String[] arr2 = num2.split("\\+");
        Integer r2 = Integer.valueOf(arr2[0]);
        String i2str = arr2[1].substring(0, arr2[1].length() - 1);
        Integer i2 = i2str.charAt(0) == '-' ? -Integer.valueOf(i2str.substring(1)) : Integer.valueOf(i2str);
        
        
        int res_r = r1 * r2 - i1 * i2;
        int res_i = r1 * i2 + r2 * i1;
        
        return res_r + "+" + res_i + "i";
    }
}
⚠️ **GitHub.com Fallback** ⚠️