leetcode-537-Complex-Number-Multiplication

描述


Given two strings representing two complex numbers.

You need to return a string representing their multiplication. Note $i^2 = -1$ according to the definition.

Example 1:

1
2
3
Input: "1+1i", "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:

1
2
3
Input: "1+-1i", "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.

Note:

  1. The input strings will not have extra blank.
  2. The input strings will be given in the form of a+bi, where the integer a and b will both belong to the range of [-100, 100]. And the output should be also in this form.

分析


复数相乘,挺简单的。$(a+bi)*(c+di)=ac+bci+adi-bd=(ac-db)+(ad+bc)i$

解决方案1(Java)


1
2
3
4
5
6
7
8
9
10
11
class Solution {
public String complexNumberMultiply(String a, String b) {
String aList[] = a.split("\\+|i");
String bList[] = b.split("\\+|i");
int aReal = Integer.parseInt(aList[0]);
int aImg = Integer.parseInt(aList[1]);
int bReal = Integer.parseInt(bList[0]);
int bImg = Integer.parseInt(bList[1]);
return (aReal*bReal - aImg*bImg) + "+" + (aReal*bImg + aImg*bReal) + "i";
}
}

题目来源