Tuesday, August 24, 2021

[LeetCode] Complex Number Multiplication

Problem: A complex number can be represented as a string on the form "real+imaginaryi" where:

  • real is the real part and is an integer in the range [-100, 100].
  • imaginary is the imaginary part and is an integer in the range [-100, 100].
  • i^2 == -1.

Given two complex numbers num1 and num2 as strings, return a string of the complex number that represents their multiplications.

Example:

Input: num1 = "1+1i", num2 = "1+1i"
Output: "0+2i"
Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i.
Input: num1 = "1+-1i", num2 = "1+-1i"
Output: "0+-2i"
Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i.


Approach: Let's say num1 is (r1 + i1i) and num2 is (r2 + i2i). Lets see how its multiplication looks like:

(r1 + i1i) * (r2 + i2i) = r1*r2 + r1*i2*i + r2*i1*i + i1*i2*i^2 

Given i^2 = -1, Now our multiplication become- 

(r1* r2 - i1 * i2) + (r1 * i2 + r2 * i1)i

Now we just need to split the num1 and num2 string on '+' and 'i' and get the real and imaginary parts of the complex number and then we just need to apply the above formula. That's it!


Implementation in C#:

    public string ComplexNumberMultiply(string num1, string num2) 

    {

        string[] nums1 = num1.Split('+', 'i');

        string[] nums2 = num2.Split('+', 'i');

        int r1 = int.Parse(nums1[0]);

        int i1 = int.Parse(nums1[1]);

        int r2 = int.Parse(nums2[0]);

        int i2 = int.Parse(nums2[1]);        

        return $"{r1 * r2 - i1 * i2}+{r1 * i2 + r2 * i1}i";

    }


Complexity: O(1)

No comments:

Post a Comment