Complex Number Multiplication

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 == -1.

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

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.

Approach

C++

#include <bits/stdc++.h>
using namespace std;

string complexNumberMultiply(string num1string num2)
{

    int n = num1.size();
    int m = num2.size();
    int abcd;
    int i = 0;
    int signa = 1signb = 1signc = 1signd = 1;
    string str = ""str2 = "";
    if (num1[i] == '-')
    {
        i++;
        signa = -1;
    }
    while (i < n && num1[i] != '+')
    {
        str += num1[i];
        i++;
    }
    i++;
    if (num1[i] == '-')
    {
        signb = -1;
        i++;
    }
    while (i < n && num1[i] != 'i')
    {
        str2 += num1[i];
        i++;
    }
    a = stoi(str);
    b = stoi(str2);
    i = 0;
    str = ""str2 = "";
    if (num2[i] == '-')
    {
        signc = -1;
        i++;
    }

    while (i < m && num2[i] != '+')
    {
        str += num2[i];
        i++;
    }
    i++;
    if (num2[i] == '-')
    {
        signd = -1;
        i++;
    }
    while (i < m && num2[i] != 'i')
    {
        str2 += num2[i];
        i++;
    }

    c = stoi(str);
    d = stoi(str2);

    int real = signa * a * c * signc - signb * b * d * signd;
    int imaginary = signa * a * d * signd + signb * b * c * signc;

    string res = "";
    res += to_string(real);
    res += "+";
    res += to_string(imaginary);
    res += "i";
    return res;
}

int main()
{
    string num1 = "1+1i"num2 = "1+1i";

    cout << complexNumberMultiply(num1num2<< "\n";

    return 0;
}


No comments:

Post a Comment