Given two strings representing two complex numbers.
You need to return a string representing their multiplication. Note i2 = -1 according to the definition.
这道题就是很简单的思路,根据公式,但是不一样的是,要注意什么时候是”+”号,什么时候是“i”,然后可以根据提交结果显示去写测试代码。
代码如下:
class Solution {
public:
string complexNumberMultiply(string a, string b) {
string x1,x2;//78+-76i//-86+72i
string y1,y2;
bool flag=true;
for(int i=0;i<a.size();i++){
if(flag&&a[i]!='+'){
x1+=a[i];
}
else if(a[i]=='+'){
flag=false;
}
else if(!flag&&a[i]!='i'&&a[i]!='+'){
x2+=a[i];
}
}
flag=true;
for(int i=0;i<b.size();i++){
if(flag&&b[i]!='+'){
y1+=b[i];
}
else if(b[i]=='+'){
flag=false;
}
else if(!flag&&b[i]!='i'&&b[i]!='+'){
y2+=b[i];
}
}
int s1,s2,s3;
s1=atoi(x1.c_str())*atoi(y1.c_str());
s2=atoi(x1.c_str())*atoi(y2.c_str())+atoi(y1.c_str())*atoi(x2.c_str());
s3=(-1)*atoi(x2.c_str())*atoi(y2.c_str());
int k=s1+s3;
string rel=to_string(k)+"+"+to_string(s2)+"i";
return rel;
}
};