您的位置:首页 > 其它

537. Complex Number Multiplication

2017-09-21 21:50 387 查看
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.

题目的要求很简单,就是给定两个复数(字符串形式string),求两个复数的乘积,并按照题目所要求的格式返回结果(字符串形式)。

其实解题思路很简单,就是解析每个复数的字符串,求出实部跟虚部,就可以计算得到最终结果。在这里,我定义了一个结构体来存储每个复数的实部跟虚部:
struct complexNumber {
int x;   // 实部
int y;   // 虚部
};
我利用了vector来实现栈的结构,以便解析出字符串中的实部和虚部。
遍历字符串中的每一个字符,只要不是+或者i,若是负号-,则-1入栈,若是数字字符,则转换为int类型入栈;
如果是+/i,说明已经可以开始计算实部/虚部,遍历栈,计算实部/虚部,计算部分的代码:
complexNumber getNumber(string s) {
complexNumber number;
number.x = 0;
number.y = 0;
vector<int> temp;
for (int i = 0; i < s.size(); i++) {
if (s[i] ==  '+') {
int count = 0;
while (!temp.empty()) {
if (temp.back() == -1) {
number.x *= -1;
} else {
number.x += temp.back() * pow(10, count);
count += 1;
}
temp.pop_back();
}
} else if (s[i] == 'i') {
int count = 0;
while (!temp.empty()) {
if (temp.back() == -1) {
number.y *= -1;
} else {
number.y += temp.back() * pow(10, count);
count += 1;
}
temp.pop_back();
}
} else {
if (s[i] == '-')
temp.push_back(-1);
else
temp.push_back(s[i] - '0');
}
}
return number;
}


最后完整的代码:
class Solution {
public:
struct complexNumber {
int x;
int y;
};

complexNumber getNumber(string s) { complexNumber number; number.x = 0; number.y = 0; vector<int> temp; for (int i = 0; i < s.size(); i++) { if (s[i] == '+') { int count = 0; while (!temp.empty()) { if (temp.back() == -1) { number.x *= -1; } else { number.x += temp.back() * pow(10, count); count += 1; } temp.pop_back(); } } else if (s[i] == 'i') { int count = 0; while (!temp.empty()) { if (temp.back() == -1) { number.y *= -1; } else { number.y += temp.back() * pow(10, count); count += 1; } temp.pop_back(); } } else { if (s[i] == '-') temp.push_back(-1); else temp.push_back(s[i] - '0'); } } return number; }

string complexNumberMultiply(string a, string b) {
int re1, im1; // string a
int re2, im2; // string b
complexNumber aNumber = getNumber(a);
complexNumber bNumber = getNumber(b);

re1 = aNumber.x;
im1 = aNumber.y;
re2 = bNumber.x;
im2 = bNumber.y;

// for result
int re = re1 * re2 - im1 * im2;
int im = im1 * re2 + re1 * im2;

stringstream result;
result << re << "+" << im << "i";

return result.str();
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: