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.
代码 :
class Solution {
public:
string complexNumberMultiply(string a, string b) {
string ans;
int areal,axushu,breal,bxushu;
areal=0;
breal=0;
axushu=0;
bxushu=0;
int i=0;
int flag=0;
for ( i=0; i<a.size(); i++)
{
if (a[i]=='-')
{
flag=1;
continue;
}
if (a[i]=='+')
break;
areal*=10;
areal+=(a[i]-'0');
}
if (flag)
areal*=(-1);
flag=0;
for (i=i+1; i<a.size(); i++)
{
if (a[i]=='i')
break;
if (a[i]=='-')
{
flag=1;
}
else
{
axushu*=10;
axushu+=(a[i]-'0');
}
}
if (flag) axushu=axushu*(-1);
flag=0;
for ( i=0; i<b.size(); i++)
{
if (b[i]=='-')
{
flag=1;
continue;
}
if (b[i]=='+')
break;
breal*=10;
breal+=(b[i]-'0');
}
if (flag)
breal*=(-1);
flag=0;
for (i=i+1; i<b.size(); i++)
{
if (b[i]=='i')
break;
if (b[i]=='-')
{
flag=1;
}
else
{
bxushu*=10;
bxushu+=(b[i]-'0');
}
}
if (flag) bxushu=bxushu*(-1);
int ansshi,ansxushu;
ansshi=0;
ansxushu=0;
ansshi=areal*breal;
ansshi-=(axushu*bxushu);
ansxushu=areal*bxushu;
ansxushu+=(axushu*breal);
ans="";
if (ansshi<0)
{
ans="-";
ansshi*=(-1);
}
ans+=to_string(ansshi);
ans+="+";
if (ansxushu<0)
{
ans+="-";
ansxushu*=(-1);
}
ans+=to_string(ansxushu);
ans+="i";
return ans;
}
};