Leetcode 537. Complex Number Multiplication
You are given two strings representing two complex numbers:
a+bi
, where a
and b
are integers, and i
represents the imaginary unit.public String complexNumberMultiply(String num1, String num2)
Input: num1 = "1+1i", num2 = "1+1i"
Output: "0+2i"
Input: num1 = "1+-1i", num2 = "1+-1i"
Output: "0+-2i"
int
type.public class ComplexNumberMultiplication {
public String complexNumberMultiply(String num1, String num2) {
// Parse both complex numbers
int[] complex1 = parseComplexNumber(num1);
int[] complex2 = parseComplexNumber(num2);
int a = complex1[0], b = complex1[1];
int c = complex2[0], d = complex2[1];
// Apply the complex number multiplication formula
int realPart = a * c - b * d;
int imaginaryPart = a * d + b * c;
// Construct the result in "real+imaginaryi" format
return realPart + "+" + imaginaryPart + "i";
}
// Helper method to parse a complex number string into its real and imaginary parts
private int[] parseComplexNumber(String num) {
String[] parts = num.split("\\+");
int realPart = Integer.parseInt(parts[0]);
int imaginaryPart = Integer.parseInt(parts[1].replace("i", ""));
return new int[]{realPart, imaginaryPart};
}
// Sample usage
public static void main(String[] args) {
ComplexNumberMultiplication sol = new ComplexNumberMultiplication();
System.out.println(sol.complexNumberMultiply("1+1i", "1+1i")); // Output: "0+2i"
System.out.println(sol.complexNumberMultiply("1+-1i", "1+-1i")); // Output: "0+-2i"
}
}
O(n)
, where n
is the number of characters in the input strings since we have to parse the entire string to extract the real and imaginary parts.O(1)
since the multiplication of two pairs of integers and string concatenation are constant-time operations.Overall, the time complexity is O(n)
.
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?