Leetcode 537. Complex Number Multiplication
Given two strings representing two complex numbers, you need to return a string representing their multiplication. Note that the complex numbers are provided in the form a+bi
where a
and b
are integers, and i
represents the imaginary unit.
a
and b
?
a+bi
?
c+di
where c
and d
are integers representing the real and imaginary parts, respectively.a
, b
, c
, and d
.(a + bi) * (c + di) = (ac - bd) + (ad + bc)i
.c+di
.#include <iostream>
#include <string>
using namespace std;
pair<int, int> parseComplexNumber(const string& complex) {
size_t plusPos = complex.find('+');
size_t iPos = complex.find('i');
int realPart = stoi(complex.substr(0, plusPos));
int imagPart = stoi(complex.substr(plusPos + 1, iPos - plusPos - 1));
return {realPart, imagPart};
}
string complexNumberMultiply(string num1, string num2) {
pair<int, int> complex1 = parseComplexNumber(num1);
pair<int, int> complex2 = parseComplexNumber(num2);
int a = complex1.first;
int b = complex1.second;
int c = complex2.first;
int d = complex2.second;
int realPart = (a * c) - (b * d);
int imagPart = (a * d) + (b * c);
return to_string(realPart) + "+" + to_string(imagPart) + "i";
}
int main() {
// Test case
string num1 = "1+1i";
string num2 = "1+1i";
cout << complexNumberMultiply(num1, num2) << endl; // Output should be "0+2i"
return 0;
}
parseComplexNumber
: This helper function takes a string in the form a+bi
, splits it into the real part and the imaginary part, and returns them as a pair<int, int>
.complexNumberMultiply
: This main function first parses inputs to extract real and imaginary parts. It then applies the complex multiplication formula to compute the real and imaginary parts of the result, and finally constructs the result string.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?