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.
1function parseComplex(complex) {
2 let parts = complex.replace('i', '').split('+');
3 return [parseInt(parts[0]), parseInt(parts[1])];
4}
5
6function complexNumberMultiply(num1, num2) {
7 let [real1, imag1] = parseComplex(num1);
8 let [real2, imag2] = parseComplex(num2);
9
10 let realPart = real1 * real2 - imag1 * imag2;
11 let imagPart = real1 * imag2 + imag1 * real2;
12
13 return `${realPart}+${imagPart}i`;
14}
15
16// Example usage
17let num1 = "1+1i";
18let num2 = "1+1i";
19console.log(complexNumberMultiply(num1, num2));
In the JavaScript implementation, the String.replace
and String.split
methods are used to dissect the complex numbers into components. The product of these numbers is computed using the same algebraic rules as before and formatted into the return string using template literals.
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.
1function parseComplexRegex(complex) {
2
The JavaScript solution applies the String.match
method with a regex pattern to efficiently extract real and imaginary parts from the input complex number strings before multiplying them and formatting the result with a template literal.