思路
先获取两个复数的实部和虚部,分别为aa,ab,ba,bb
.然后乘起来,实部为(aa*ba-ab*bb)
,虚部为(aa*bb+ab*ba)i
解答
class Solution {
public:
string complexNumberMultiply(string a, string b) {
string res;
if(a.empty() || b.empty()) return res;
int p=0;
//aa代表复数a的实部, ab代表复数a的虚部
//下面的程序用于获取复数a和b的实部和虚部,程序不做简化了
int aa=0,ba=0,ab=0,bb=0;
int flag=1;
while(a[p]!= '+')
{
if(a[p]=='-')
{
flag=-1;
++p;
}
else
aa=aa*10+a[p++]-'0';
}
aa=flag*aa;
++p;
flag=1;
while(a[p]!= 'i')
{
if(a[p]=='-')
{
flag=-1;
++p;
}
else
ab=ab*10+a[p++]-'0';
}
ab=flag*ab;
p=0;
flag=1;
while(b[p]!= '+')
{
if(b[p]=='-')
{
flag=-1;
++p;
}
else
ba=ba*10+b[p++]-'0';
}
ba=flag*ba;
flag=1;
++p;
while(b[p]!= 'i')
{
if(b[p]=='-')
{
flag=-1;
++p;
}
else
bb=bb*10+b[p++]-'0';
}
bb=flag*bb;
//下面的程序用于得出结果
res+= to_string(aa*ba-ab*bb)+ '+';
res+= to_string(aa*bb+ab*ba)+'i';
return res;
}
};