您的位置:首页 > 编程语言 > C语言/C++

leetcode 537. Complex Number Multiplication 复数乘法 + C++中stringstream很好示例

2017-12-17 14:31 411 查看
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.

本题意很简单,就是计算复数的乘法,

这道题最大的启发就是C++的stringstream真的很好用

建议和这一道题leetcode 539. Minimum Time Difference C++中的stringstream真的很好用 一起学习

代码如下:

#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <string>
#include <climits>
#include <algorithm>
#include <sstream>
#include <functional>
#include <bitset>
#include <numeric>
#include <cmath>

using namespace std;

class Solution
{
public:
string complexNumberMultiply(string a, string b)
{
int ra, ia, rb, ib;
char buff;
stringstream aa(a), bb(b), ans;
aa >> ra >> buff >> ia >> buff;
bb >> rb >> buff >> ib >> buff;
ans << ra*rb - ia*ib << "+" << ra*ib + rb*ia << "i";
return ans.str();
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: