537. Complex Number Multiplicati
2018-01-13 本文已影响0人
matrxyz
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.
Note:
The input strings will not have extra blank.
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.
Solution:
思路:
// (x1 + iy1)* (x2 + iy2) = (x1x2 - y1y2 + i(x1y2 + x2y1))
Time Complexity: O(N) Space Complexity: O(1)
Solution Code:
// (x1 + iy1)* (x2 + iy2) = (x1x2 - y1y2 + i(x1y2 + x2y1))
class Solution {
public String complexNumberMultiply(String a, String b) {
int p1 = a.indexOf('+'), p2 = b.indexOf('+'), n1 = a.length() - 1, n2 = b.length() - 1;
int x1 = Integer.valueOf(a.substring(0, p1)), y1 = Integer.valueOf(a.substring(p1 + 1, n1));
int x2 = Integer.valueOf(b.substring(0, p2)), y2 = Integer.valueOf(b.substring(p2 + 1, n2));
return (x1 * x2 - y1 * y2) + "+" + (x1 * y2 + x2 * y1) + "i";
}
}