longer but proper C++ code


  • 0
    G
    class Solution {
    public:
    
        struct Comp
        {
            int C;
            int R;
            
            Comp(int r, int c)
            :
            R(r),
            C(c)
            {
            }
            
            Comp(int r, std::string &c)
            :
            R(r)
            {
                if(c.empty())
                {
                    C = 0;
                }
                else
                {
                    auto Loc = c.find("i");
                    istringstream ss(c.substr(0,Loc));
                    ss >> C;
                }
            }
            
            Comp operator*(const Comp &Other)
            {
                long long  Real = Other.R*R;
                long long  Img = Other.C*R + C*Other.R;
                Real += (C*Other.C)*-1;
                
                return Comp(Real,Img);
            }
            
            template <typename IS>
            friend
            IS& operator<<(IS &out, const Comp &Cmp)
            {
                out << Cmp.R << "+" << Cmp.C << "i";
                return out;
            }
        };
    
        string complexNumberMultiply(string a, string b)
        {
            auto F1 = a.find("+");
            auto F2 = b.find("+");
            
            string af,as,bf,bs;
            af = a.substr(0,F1);
            
            if(F1 != std::string::npos)
            {
                as = a.substr(F1 + 1);
            }
            else
            {
                as = "";
            }
            
            bf = b.substr(0,F2);
            
            if(F2 != std::string::npos)
            {
                bs = b.substr(F2 + 1);
            }
            else
            {
                bs = "";
            }
            
            int R1 = 0,R2 = 0;
            istringstream ss1(af);
            istringstream ss2(bf);
            ss1 >> R1;
            ss2 >> R2;
         
            Comp C1(R1,as);
            Comp C2(R2,bs);
            
            ostringstream Res;
            Res << (C1*C2);
            return Res.str();
        }
    };

Log in to reply
 

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