537. Complex Number

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.

Constraints:

• num1 and num2 are valid complex numbers.

Solution To the Above Question

class Solution {
public:
int getInt(string num){
int i=0;
int number=0;
bool flag=false;
if(num[0]=='-'){
flag=true;
}
if(!flag){
while(num[i]!='+'){
i++;
}
int k=i;
for(int j=0j<kj++){
number=(num[j]-'0')*pow(10,i-1) +number;
i--;
}
return number;
}
if(flag){
while(num[i]!='+'){
i++;
}
int k=i;
for(int j=1j<kj++){
number=(num[j]-'0')*pow(10,i-2) +number;
i--;
}
return -1*number;
}
return number;
}

int getInt2(string num){
int i=0;
int t=0;
int n=num.length();
int number=0;
while(num[i]!='+'){
i++;
}
while(num[t]!='i'){
t++;
}
bool flag=false;
if(num[i+1]=='-'){
flag=true;
}
if(!flag){

int k=t-i;
for(int j=i+1j<n-1j++){
number=(num[j]-'0')*pow(10,k-2) +number;
k--;
}
return number;
}
if(flag){

int k=t-i-1;
for(int j=i+2j<n-1j++){
number=(num[j]-'0')*pow(10,k-2) +number;
k--;
}
return -1*number;
}
return number;
}

string complexNumberMultiply(string num1string num2) {
int r1=getInt(num1);
int i1=getInt2(num1);
int r2=getInt(num2);
int i2=getInt2(num2);
cout<<r1<<" "<<r2<<" "<<i1<<" "<<i2;
int ans1=r1*r2-i1*i2;
int ans2=r1*i2+r2*i1;