Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

537. Complex Number Multiplication

MathStringSimulation

Explanation:

To multiply two complex numbers represented in the form of "a+bi", we need to perform the following steps:

  1. Parse the real and imaginary parts of both complex numbers.
  2. 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.
  3. Format the result back into the string form "a+bi". :
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";
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.