LeetCode 537. Complex Number Multiplication

来源:互联网 发布:youtube 批量下载软件 编辑:程序博客网 时间:2024/05/20 06:41

题目

Given two strings representing two complex numbers.
You need to return a string representing their multiplication. Note i2 = -1 according to the definition.

Example:

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.

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.

思考

题目为复数乘法,对输入的限制高(实部和虚部就算是0也要写上去;即使虚部为负数,中间的加号也要有),因此获得各个部分比较简单,只需要将string转换为int就能算出结果的实部和虚部。

答案

c++
用stringstream进行string和int的转换。

class Solution {public:    string complexNumberMultiply(string a, string b) {        int plusIndex1 = a.find('+');        int plusIndex2 = b.find('+');        int aReal, bReal, aImag, bImag;        stringstream ss;        ss << a.substr(0, plusIndex1);        ss >> aReal;        ss.clear();        ss << b.substr(0, plusIndex2);        ss >> bReal;        ss.clear();        ss << a.substr(plusIndex1 + 1, a.size() - plusIndex1 - 2);        ss >> aImag;        ss.clear();        ss << b.substr(plusIndex2 + 1, b.size() - plusIndex2 - 2);        ss >> bImag;        ss.clear();        string result1 = "", result2 = "";        int resultReal, resultImag;        resultReal = aReal * bReal - aImag * bImag;        resultImag = aReal * bImag + aImag * bReal;        ss << resultReal;        ss >> result1;        ss.clear();        ss << resultImag;        ss >> result2;        string result = result1 + '+' + result2 + 'i';        return result;    }};
原创粉丝点击