[LeetCode]537. Complex Number Multiplication

題目

Given two strings representing two complex numbers.

You need to return a string representing their multiplication. Note i2 = -1 according to the definition.

Example 1:

Input: "1+1i", "1+1i"
Output: "0+2i"
Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i.

**Example 2: **

Input: "1+-1i", "1+-1i"
Output: "0+-2i"
Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i.

Note:

  1. The input strings will not have extra blank.
  2. The input strings will be given in the form of a+bi, where the integer a and b will both belong to the range of [-100, 100]. And the output should be also in this form.
難度

Medium

方法

這題難度雖然標(biāo)記為Medium,但是比較簡單。對于給定字符串a1+b1ia2+b2i,分別提取出a1,b1,a2,b2,最后的結(jié)果為(a1*a2-b1*b2)+(a1*b2+a2*b1)i

python代碼
class Solution(object):
    def complexNumberMultiply(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        a1, b1 = map(int, a[:-1].split("+"))
        a2, b2 = map(int, b[:-1].split("+"))
        return "%s+%si" % (a1*a2-b1*b2, a1*b2+a2*b1)

assert Solution().complexNumberMultiply("1+1i", "1+1i") == "0+2i"
assert Solution().complexNumberMultiply("1+-1i", "1+-1i") == "0+-2i"
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,936評論 0 33
  • 一路走,一路花開次第,朋友的數(shù)量從來不和年紀(jì)成正比。有些朋友,我們走著走著就弄丟了。寂寞的時候,一支煙,一盞暖胃的...
    風(fēng)也醉人閱讀 269評論 0 0
  • 出自:http://www.xiaoboswift.com/course/54
    jetgege閱讀 203評論 0 0
  • 2016年5月24號國道102上,一個穿著黑色上衣,及膝黑紅格子相間的短裙的女孩,右手擦著雙眼不住流出的淚,左手向...
    小胡涂神兒閱讀 263評論 0 0
  • 兒子放學(xué)以后,經(jīng)常要求我?guī)V場。一到廣場上,他就像脫韁的小野馬一樣,不知疲倦的到處跑,把廣場上的健身器材挨個試...
    夏煙閱讀 223評論 0 0

友情鏈接更多精彩內(nèi)容