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.
1public class ComplexNumber {
2 private int real, imag;
3
4 public ComplexNumber(String complex) {
5 String[] parts = complex.split("[+i]");
6 this.real = Integer.parseInt(parts[0]);
7 this.imag = Integer.parseInt(parts[1]);
8 }
9
10 public static String complexNumberMultiply(String num1, String num2) {
11 ComplexNumber c1 = new ComplexNumber(num1);
12 ComplexNumber c2 = new ComplexNumber(num2);
13
14 int realPart = c1.real * c2.real - c1.imag * c2.imag;
15 int imagPart = c1.real * c2.imag + c1.imag * c2.real;
16
17 return realPart + "+" + imagPart + "i";
18 }
19
20 public static void main(String[] args) {
21 String num1 = "1+1i";
22 String num2 = "1+1i";
23 System.out.println(complexNumberMultiply(num1, num2));
24 }
25}
In the Java implementation, a constructor is used to parse and separate the real and imaginary parts of the complex number using String
manipulation and Integer.parseInt
. Multiplication and result formatting are straightforward, leveraging the predefined behavior in Java for string 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.
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.