1.题目
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.
2.分析
本题主要考点: 从字符串中提取复数
比较笨的方法是遍历字符串,手动提取实部,虚部
便利的方法例如:
c++ stringstream
python split
3.代码
c++ stringstream
class Solution {
public:
string complexNumberMultiply(string a, string b) {
int a_Re, a_Im;
int b_Re, b_Im;
char buff;
stringstream A(a), B(b),ans;
A >> a_Re >> buff >> a_Im >> buff;
B >> b_Re >> buff >> b_Im >> buff;
ans << a_Re*b_Re - a_Im*b_Im << "+" << a_Re*b_Im + a_Im*b_Re << "i";
return ans.str();
}
};
python split
class Solution(object):
def complexNumberMultiply(self, a, b):
ra,ia=map(int,a[:-1].split('+'))
rb,ib=map(int,b[:-1].split('+'))
return '%d+%di'%(ra*rb-ia*ib,ra*ib+rb*ia)
手动遍历
class Solution {
public:
void get_complex(string s, int& Re, int& Im) {
int i = 0;
int sign_Re = 1;
int sign_Im = 1;
if (s[i] == '-') {
sign_Re = -1;
++i;
}
while (s[i] != '+') {
Re = Re * 10 + s[i] - '0';
++i;
}
++i;
if (s[i] == '-')
{
sign_Im = -1;
++i;
}
while (s[i] != 'i') {
Im = Im * 10 + s[i] - '0';
++i;
}
Re *= sign_Re;
Im *= sign_Im;
}
string complexNumberMultiply(string a, string b) {
int a_Re=0, a_Im = 0;
int b_Re=0, b_Im = 0;
get_complex(a, a_Re, a_Im);
get_complex(b, b_Re, b_Im);
int Re = a_Re*b_Re - a_Im*b_Im;
int Im = a_Re*b_Im + a_Im*b_Re;
return to_string(Re) + "+" + to_string(Im) + "i";
}
};