# 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 + i
``````

2

`````` + 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 + i
``````

2

`````` - 2 * i = -2i, and you need convert it to the form of 0+-2i.
``````

Note:

1. The input strings will not have extra blank.
2. 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.

``````class Solution {
public:
string complexNumberMultiply(string a, string b) {
int n1 = a.size(), n2 = b.size();
auto p1 = a.find_last_of("+"), p2 = b.find_last_of("+");
int a1 = stoi(a.substr(0, p1)), b1 = stoi(b.substr(0, p2));
int a2 = stoi(a.substr(p1 + 1, n1 - p1 - 2));
int b2 = stoi(b.substr(p2 + 1, n2 - p2 - 2));
int r1 = a1 * b1 - a2 * b2, r2 = a1 * b2 + a2 * b1;
}
};
``````

``````class Solution {
public:
string complexNumberMultiply(string a, string b) {
istringstream is1(a), is2(b);
int a1, a2, b1, b2, r1, r2;
char plus;
is1 >> a1 >> plus >> a2;
is2 >> b1 >> plus >> b2;
r1 = a1 * b1 - a2 * b2, r2 = a1 * b2 + a2 * b1;
}
};
``````

``````class Solution {
public:
string complexNumberMultiply(string a, string b) {
int a1, a2, b1, b2, r1, r2;
sscanf(a.c_str(), "%d+%di", &a1, &a2);
sscanf(b.c_str(), "%d+%di", &b1, &b2);
r1 = a1 * b1 - a2 * b2, r2 = a1 * b2 + a2 * b1;
}
};
``````

https://discuss.leetcode.com/topic/84261/java-3-liner

https://discuss.leetcode.com/topic/84382/c-using-stringstream

https://discuss.leetcode.com/topic/84323/java-elegant-solution

https://discuss.leetcode.com/topic/84508/cpp-solution-with-sscanf

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation