[LeetCode] Complex Number Multiplication

537. Complex Number Multiplication

A complex number can be represented as a string on the form “real+imaginaryi” where:

  • real is the real part and is an integer in the range [-100, 100].
  • imaginary is the imaginary part and is an integer in the range [-100, 100].
  • i2 == -1.

Given two complex numbers num1 and num2 as strings, return a string of the complex number that represents their multiplications.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
pair<int, int> parse(string& s) {
int i = 0, n = s.length();
int a = 0, b = 0;
int signa = 1, signb = 1;
if(s[0] == '-') {
signa = -1, i = 1;
}

while(i < n and s[i] != '+') {
a = a * 10 + (s[i++] & 0b1111);
}
i++;
if(s[i] == '-') {
signb = -1, i+=1;
}
while(i < n and s[i] != 'i') {
b = b * 10 + (s[i++] & 0b1111);
}

return {signa*a,signb*b};
}
public:
string complexNumberMultiply(string A, string B) {
auto [aa, ab] = parse(A);
auto [ba, bb] = parse(B);
auto front = aa * ba - ab * bb;
auto back = aa * bb + ba * ab;
return to_string(front) + "+" + to_string(back) + "i";
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/28/PS/LeetCode/complex-number-multiplication/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.