537. Complex Number Multiplication

题目描述:

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]. And the output should be also in this form.

解题思路:

题目本质很简单,解析输入参数稍微繁琐点。

代码:

 1 class Solution {
 2 public:
 3     string complexNumberMultiply(string a, string b) {
 4         int num1, num2, num3, num4;
 5         int res1, res2;
 6         string sig1, sig2, res;
 7         parse(num1, num2, sig1, a);
 8         parse(num3, num4, sig2, b);
 9         res1 = num1 * num3 - num2 * num4;
10         res2 = num1 * num4 + num2 * num3;
11         res = to_string(res1) + "+" +to_string(res2) + "i";
12         return res;
13     }
14     void parse(int& a, int& b, string& sig, const string& input) {
15         size_t plus =  input.find("+");
16         size_t i = input.find("i");
17         size_t minus = input.find("-");
18         a = stoi(input.substr(0, plus));
19         if (minus != string::npos) {
20             b = stoi(input.substr(plus+1, i-(plus+1)));
21             sig = "-";
22         } else {
23             b = stoi(input.substr(plus+1, i-(plus+1)));
24             sig = "+";
25         }
26     }
27 };

 

posted @ 2018-08-05 10:56  gszzsg  阅读(94)  评论(0编辑  收藏  举报