[刷题防痴呆] 0537 - 复数乘法 (Complex Num

2021-10-14  本文已影响0人  西出玉门东望长安

题目地址

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

题目描述

537. 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].
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 {
    public String complexNumberMultiply(String num1, String num2) {
        String[] strs1 = num1.split("\\+");
        String[] strs2 = num2.split("\\+");

        int a = Integer.parseInt(strs1[0]);
        int b = Integer.parseInt(strs1[1].substring(0, strs1[1].length() - 1));
        int c = Integer.parseInt(strs2[0]);
        int d = Integer.parseInt(strs2[1].substring(0, strs2[1].length() - 1));

        StringBuffer sb = new StringBuffer();
        sb.append(a * c - b * d);
        sb.append("+");
        sb.append(b * c + a * d);
        sb.append("i");

        return sb.toString();
    }
}
上一篇下一篇

猜你喜欢

热点阅读