LeetCode:Complex Number Multiplication

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.

思路:思路比较直接,关键在于找到各个方程式的系数就可以了。
 1 int getpos(string s,char c)
 2 {
 3     int len = s.length();
 4     int i = 0;
 5     for (; i < len; i++)
 6     {
 7         if (s[i] == c)
 8             return i;
 9     }
10 }
11 int geta(string s)
12 {
13     return stoi(s.substr(0, getpos(s, '+') + 1).c_str());
14 }
15 int getb(string s)
16 {
17     return stoi(s.substr(getpos(s, '+') + 1,s.length()-getpos(s,'+')-1).c_str());
18 }
19 string complexNumberMultiply(string a, string b) {
20     
21     ostringstream s1,s2;
22     s1 << geta(a)*geta(b) - getb(a)*getb(b);
23     s2 << geta(a)*getb(b) + getb(a)*geta(b);
24     return s1.str()+"+"+s2.str()+"i";
25 }

如果你有任何疑问或新的想法,欢迎在下方评论。

posted @ 2017-04-10 21:21  陆小风不写代码  阅读(165)  评论(0编辑  收藏  举报