Sponsored
Sponsored
This approach involves parsing the given strings to separate the real and imaginary components of each complex number. Once separated, apply the distributive property of multiplication for complex numbers: (a+bi)(c+di) = ac + adi + bci + bdi^2. Substitute i^2 with -1 and then combine the real and imaginary parts for the final output string.
Time Complexity: O(1) because the operations are constant-time.
Space Complexity: O(1) since it only uses a fixed amount of space for the variables and a small dynamic allocation for the output string.
1#include <iostream>
2#include <string>
3#include <sstream>
4
5void parseComplex(const std::string& complex, int& real, int& imaginary) {
6 char plus, i;
7 std::istringstream iss(complex);
8 iss >> real >> plus >> imaginary >> i;
9}
10
11std::string complexNumberMultiply(std::string num1, std::string num2) {
12 int real1, imag1, real2, imag2;
13 parseComplex(num1, real1, imag1);
14 parseComplex(num2, real2, imag2);
15
16 int realPart = real1 * real2 - imag1 * imag2;
17 int imagPart = real1 * imag2 + imag1 * real2;
18
19 return std::to_string(realPart) + "+" + std::to_string(imagPart) + "i";
20}
21
22int main() {
23 std::string num1 = "1+1i";
24 std::string num2 = "1+1i";
25 std::cout << complexNumberMultiply(num1, num2) << std::endl;
26 return 0;
27}
This C++ solution utilizes std::istringstream
to parse the complex numbers. The multiplication operation is performed as per the formula (a+bi)(c+di) = ac + adi + bci + bdi^2. The result is converted back to a string using std::to_string
and concatenation.
In this approach, regular expressions are used to parse the complex number strings. This involves defining a regex pattern to capture the real and imaginary components. After extracting these components, multiplication is performed using the same algebraic rules, and the result is formatted for output.
Time Complexity: O(1) since the regex operation is effectively constant time for fixed-size strings.
Space Complexity: O(1) involving fixed-size auxiliary storage for components and result.
1import re
2
3def parse_complex_regex(
Using re.match
in Python with a regular expression captures the real and imaginary parts directly. The parsed integers are used for multiplication, with results formatted back into strings in the expected form using Python's f-string syntax.