Given two strings representing two complex numbers.
You need to return a string representing their multiplication. Note i2 = -1 according to the definition.
Example 1:
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:
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.
----------------------------------------------------------------------------------------------------------------------------------------------------------
这道题思路很简单,就是分割字符串然后按照公式进行计算即可。
public class Solution {
public String complexNumberMultiply(String a, String b) {
int [] result1 = transferForm(a);
int [] result2 = transferForm(b);
StringBuilder multiResult = new StringBuilder();
int partOne = result1[0] * result2[0];
int partTwo = result1[0] * result2[1] + result1[1]*result2[0];
int partThree = result1[1]*result2[1]*(-1);
int combinePartOne = partOne + partThree;
multiResult.append(combinePartOne+"+"+partTwo+"i");
System.out.println("multip:"+multiResult);
return multiResult.toString();
}
public static int[] transferForm(String str){
int[] complexNum = new int[4];
String[] splited = null;
splited = str.split("\\+");
complexNum[0] = Integer.valueOf(splited[0]);
String num = splited[1].split("i")[0];
complexNum[1]=Integer.valueOf(num);
return complexNum;
}
}