Complex Number Multiplication

来源:互联网 发布:贵金属网络销售怎么样 编辑:程序博客网 时间:2024/06/05 10:50

 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:

  1. The input strings will not have extra blank.
  2. The input strings will be given in the form of a+bi, where the integera and b will both belong to the range of [-100, 100]. Andthe 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;            }};




0 0
原创粉丝点击