LeetCode 537: Complex Number Multiplication Solution
Master LeetCode problem 537 (Complex Number Multiplication), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
537. Complex Number Multiplication
Problem Explanation
Explanation:
To multiply two complex numbers represented in the form of "a+bi", we need to perform the following steps:
- Parse the real and imaginary parts of both complex numbers.
- Calculate the real and imaginary parts of the result using the formula: (a1 * a2 - b1 * b2) + (a1 * b2 + a2 * b1)i, where a1, b1 are the real and imaginary parts of the first number, and a2, b2 are the real and imaginary parts of the second number.
- Format the result back into the string form "a+bi". :
Solution Code
class Solution {
public String complexNumberMultiply(String num1, String num2) {
String[] num1Parts = num1.split("\\+");
String[] num2Parts = num2.split("\\+");
int a1 = Integer.parseInt(num1Parts[0]);
int b1 = Integer.parseInt(num1Parts[1].replace("i", ""));
int a2 = Integer.parseInt(num2Parts[0]);
int b2 = Integer.parseInt(num2Parts[1].replace("i", ""));
int real = a1 * a2 - b1 * b2;
int imaginary = a1 * b2 + a2 * b1;
return real + "+" + imaginary + "i";
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 537 (Complex Number Multiplication)?
This page provides optimized solutions for LeetCode problem 537 (Complex Number Multiplication) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 537 (Complex Number Multiplication)?
The time complexity for LeetCode 537 (Complex Number Multiplication) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 537 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 537 in Java, C++, or Python.