Skip to main content

Complex Number Multiplication

Problem Description​

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].
  • i2==−1i^2 == -1.

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

Examples​

Example 1:

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.

Example 2:

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.

Constraints​

  • num1 and num2 are valid complex numbers.

Solution for Complex Number Multiplication​

Approach 1:​

Algorithm​

Multiplication of two complex numbers can be done as:

(a+ib)×(x+iy)=ax+i2by+i(bx+ay)=ax−by+i(bx+ay)(a+ib)×(x+iy)=ax+i^2by+i(bx+ay)=ax−by+i(bx+ay)

We simply split up the real and the imaginary parts of the given complex strings based on the '+' and the 'i' symbols. We store the real parts of the two strings a and b as x[0] and y[0] respectively and the imaginary parts as x[1] and y[1] respectively. Then, we multiply the real and the imaginary parts as required after converting the extracted parts into integers. Then, we again form the return string in the required format and return the result.

Code in Different Languages​

Written by @Shreyash3087
#include <iostream>
#include <string>
#include <sstream>

class Solution {
public:
std::string complexNumberMultiply(std::string num1, std::string num2) {
auto parseComplex = [](const std::string& s) -> std::pair<int, int> {
std::stringstream ss(s);
std::string realPart, imagPart;
getline(ss, realPart, '+');
getline(ss, imagPart, 'i');
return {std::stoi(realPart), std::stoi(imagPart)};
};

auto [a_real, a_img] = parseComplex(num1);
auto [b_real, b_img] = parseComplex(num2);

int real = a_real * b_real - a_img * b_img;
int img = a_real * b_img + a_img * b_real;

return std::to_string(real) + "+" + std::to_string(img) + "i";
}
};


Complexity Analysis​

Time Complexity: O(1)O(1)​

Reason: Here splitting takes constant time as length of the string is very small (<20).

Space Complexity: O(1)O(1)​

Reason: Constant extra space is used.

References​


Authors:

Loading...