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 integer a and b will both belong to the range of [-100, 100]. Andthe output should be also in this form.
     1 class Solution {
     2 public:
     3     int str2num(string s)
     4     {
     5         int num;
     6         stringstream ss(s);
     7         ss >> num;
     8         return num;
     9     }
    10     string num2str(double i)
    11     {
    12         stringstream ss;
    13         ss << i;
    14         return ss.str();
    15     }
    16     string complexNumberMultiply(string a, string b) {
    17         int alen = a.size();
    18         int blen = b.size();
    19         string a1 = "", a2 = "", b1 = "", b2 = "";
    20         int aj = 0; int i;
    21         for (i = 0; i < alen; i++)
    22         {
    23             if (a[i] == '+')
    24                 aj = i;
    25         }
    26         int  bj = 0; int j;
    27         for (j = 0; j < blen; j++)
    28         {
    29             if (b[j] == '+')
    30                 bj = j;
    31         }
    32         a1 = a.substr(0, aj);
    33         a2 = a.substr(aj + 1, alen - aj - 1);
    34         b1 = b.substr(0, bj);
    35         b2 = b.substr(bj + 1, blen - bj - 1);
    36         int A1 = str2num(a1);
    37         int A2 = str2num(a2);
    38         int B1 = str2num(b1);
    39         int B2 = str2num(b2);
    40         int first = A1*B1 - A2*B2;
    41         int second = A1*B2 + A2*B1;
    42         return  num2str(first) + "+" + num2str(second) + "i";
    43     }
    44 };
     1 class Solution {
     2 public:
     3     string complexNumberMultiply(string a, string b) {
     4         int alen = a.size();
     5         int blen = b.size();
     6         string a1 = "", a2 = "", b1 = "", b2 = "";
     7         int aj =a.find('+');
     8         int bj = b.find('+');
     9         a1 = a.substr(0, aj);
    10         a2 = a.substr(aj + 1, alen - aj - 1);
    11         b1 = b.substr(0, bj);
    12         b2 = b.substr(bj + 1, blen - bj - 1);
    13         int A1 = stoi(a1);
    14         int A2 = stoi(a2);
    15         int B1 = stoi(b1);
    16         int B2 = stoi(b2);
    17         int first = A1*B1 - A2*B2;
    18         int second = A1*B2 + A2*B1;
    19         return  to_string(first) + "+" + to_string(second) + "i";
    20     }
    21 };

     

posted on 2017-07-19 14:29  无惧风云  阅读(145)  评论(0编辑  收藏  举报