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.
思路:
首先将 ‘+’找到,将字符串分成左右两部分,然后分别转换成整数就可以了。
int stringToint(string a,int& real,int& virtu) { int i = 0; for (; i < a.size();i++)//找到+号 位置i { if (a[i] == '+') break; } real = atoi(a.substr(0, i).c_str()); virtu = atoi(a.substr(i+1,a.size()-i-2).c_str()); //cout << real << " " << virtu << endl; return 0; } string complexNumberMultiply(string a, string b) { if (a.size() == 0 || b.size() == 0) return "0"; int real1, virtu1, real2, virtu2,real,virtu; stringToint(a, real1, virtu1); stringToint(b, real2, virtu2); real = real1*real2 - virtu1*virtu2; virtu = real1*virtu2 + virtu1*real2; char resu[128]; sprintf(resu, "%d+%di", real, virtu); return resu; }