第十二周作业:
537. 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.
思路:假设输入的复数为ra+iai, rb+ibi
有复数乘法公式:(ra+iai)*(rb+ibi) = (rarb - iaib) + (raib+rbia)i
使用最近才列入c++标准的<sstream>库中的stringstream可以很方便的帮我们解决这个问题。
stringstream可以按输入流的顺序匹配字符串中需要的部分转换为对应的类型和操作符op,忽略不需要的字符。
例如1+-1i,使用stringstreamin>>ra>>op>>ia语句(其中ra和ia是int型),会自动匹配ra=1,op=+,ia=-1,忽略后面的i。
因此可以方便的读入两个复数。之后再按照公式输出即可。
代码如下:
class Solution {
public:
string complexNumberMultiply(string a, string b) {
int ra, ia, rb, ib;
char op;
stringstream ssa(a), ssb(b);
ssa >> ra >> op >> ia;
ssb >> rb >> op >> ib;
string result = to_string(ra * rb - ia * ib);
result += "+";
result += to_string(ra * ib + rb * ia);
result += "i";
return result;
}
};