Implementing all kinds of operation for Complex


  • 0
    5
    struct Complex {
        int real;
        int imaginary;
    
        Complex(int r, int i):real(r),imaginary(i){};
        Complex operator + (const Complex & C) const{
           return Complex(real + C.real,imaginary + C.imaginary);
        }
        Complex  operator - (const Complex & C) const{
             return Complex(real - C.real,imaginary - C.imaginary);
        }
        Complex  operator * (const Complex & C) const{
            return Complex((real * C.real) - (imaginary * C.imaginary), (imaginary * C.real) + (real * C.imaginary));
        }
    };
    class Solution {
    public:
        string complexNumberMultiply(string a, string b) {
            Complex c1 = strToComplex(a);
            Complex c2 = strToComplex(b);
            Complex c3 = c1 * c2;
            return comToString(c3);
            
        }
    private:
        Complex strToComplex(string str) {
            int index = 0;
            for (int i = 0; i < str.size(); ++i) {
                if (str[i] == '+') {
                    index = i;
                    break;
                }
            }
            string real = str.substr(0, index);
            string imaginary = str.substr(index + 1);
            imaginary.pop_back();
            cout << real <<" "<< imaginary<<endl;
            return Complex(stoi(real), stoi(imaginary));
            
        }
        string comToString(Complex c) {
            return to_string(c.real) +"+"+to_string(c.imaginary) + 'i';
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.