clueless coding // TODO: be smarter

LeetCode 537. Complex Number Multiplication: C++ Solution



Problem Statement


Given two complex numbers in string format, return a string that represen s their product.

Function Signature (C++):
  string complexNumberMultiply(string a, string b)

Inputs:
  a = "1+1i"
  b = "1+1i"

Outputs:
"0 + 2i"

(1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i

Inputs:
  a = "1+-1i"
  b = "1+-1i"

Outputs:
"0+-2i"

(1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i



TL;DR Code Solution


string complexNumberMultiply(string a, string b) {
    int ra, ia, rb, ib;
    char buff;
    stringstream aa(a), bb(b), ans;
    aa >> ra >> buff >> ia >> buff;
    bb >> rb >> buff >> ib >> buff;
    ans << ra*rb - ia*ib << "+" << ra*ib + rb*ia << "i";
    return ans.str();
}