python o(n) solution, maybe a little bit tedious


  • 0
    X
    def complexNumberMultiply(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        a_real, a_img = self.discompose(a)[0], self.discompose(a)[1]
        b_real, b_img = self.discompose(b)[0], self.discompose(b)[1]
        real = a_real * b_real - a_img * b_img
        img = a_real * b_img + a_img * b_real
        return '{}+{}i'.format(str(real), str(img))
        
    def discompose(self, s):
        real = 0
        i = 0 if s[0].isdigit() else 1
        sign_real = 1 - 2 * (s[0] == '-')
        while s[i] != '+':
            real = real * 10 + int(s[i]) 
            i += 1
        real *= sign_real
            
        img = 0
        j = i + 1 if s[i + 1].isdigit() else i + 2
        sign_img = 1 - 2 * (s[i + 1] == '-')
        while s[j] != 'i':
            img = img * 10 + int(s[j])
            j += 1
        img *= sign_img
        
        return real, img

Log in to reply
 

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