Python, Straightforward with Explanation


  • 3

    This is a straightforward string manipulation problem. Our goal is to extract the integers from the strings, deduce the answer, then output the answer in the required format.

    First, we should extract the integers from the string representation of the complex number. We split a string like "a+bi" into parts first = "a", second = "bi", then truncate the "i" part in second. We return these as integers.

    After, we perform the complex number multiplication: (ar + i * ai) * (br + i * bi) = ar * br + i^2 * ai * bi + (ar * bi + ai * br) i. Of course, i^2 can be simplified to -1. We then format the output correctly using 'format'.

    def convert_to_tuple(S):
      first, second = S.split('+')
      second = second[:-1]
      return int(first), int(second)
    
    ar, ai = convert_to_tuple(a)
    br, bi = convert_to_tuple(b)
    real = ar * br - ai * bi
    imag = ar * bi + br * ai
    return "{}+{}i".format(real, imag)
    

    Note: I try to focus my editorials on the most repeatable and instructive solutions, not the most clever or short.


Log in to reply
 

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