Simple python solution with explanation


  • 0
    C
    def complexNumberMultiply(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        # real and imaginary parts of a and b
        ra, ca = self.getRealAndIm(a)
        rb, cb = self.getRealAndIm(b)
        # z = (x+iy)(a+ib) = (xa-yb) + i(xb+ay)
        res = str(ra*rb-ca*cb) + '+' + str(ra*cb+ca*rb) + 'i'
        return res
    
    # Extract real and imaginary parts of a complex number
    def getRealAndIm(self, string):
        r, c = string.split('+')
        # extract the imaginary part of a complex number, which is a coefficient in front of imaginary unit
        c = c[:-1]
        return int(r), int(c)

Log in to reply
 

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