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.
1def parse_complex(complex):
2 real, imag = complex.split('+')
3 imag = imag.rstrip('i')
4 return int(real), int(imag)
5
6def complexNumberMultiply(num1, num2):
7 real1, imag1 = parse_complex(num1)
8 real2, imag2 = parse_complex(num2)
9
10 real_part = real1 * real2 - imag1 * imag2
11 imag_part = real1 * imag2 + imag1 * real2
12
13 return f"{real_part}+{imag_part}i"
14
15# Example usage
16num1 = "1+1i"
17num2 = "1+1i"
18print(complexNumberMultiply(num1, num2))
Python's string processing abilities make it easy to split the complex number into its components. The split
method is used to separate the real and imaginary parts. After computing these parts using the complex multiplication formula, the result is formatted into the expected form using an f-string.
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.