LC 537. Complex Number Multiplication
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.
Runtime: 4 ms, faster than 14.90% of C++ online submissions for Complex Number Multiplication.
class Solution {
public:
pair<int,int> get_ab(string s){
int addpos = 0;
for(int i=0; i<s.size(); i++){
if(s[i] == '+') addpos = i;
}
auto p = make_pair<int,int>(0,0);
p.first = stoi(s.substr(0,addpos));
p.second = stoi(s.substr(addpos+1,s.size()-addpos-2));
return p;
}
string complexNumberMultiply(string a, string b) {
auto a_ab = get_ab(a);
auto b_ab = get_ab(b);
int x1 = a_ab.first, y1 = a_ab.second, x2 = b_ab.first, y2 = b_ab.second;
string reta = to_string(x1*x2 - y1*y2);
string retb = to_string(x1*y2 + x2*y1);
return reta + "+" + retb + "i";
}
};