[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

方法

这题难度虽然标记为Medium,但是比较简单。对于给定字符串a1+b1ia2+b2i,分别提取出a1,b1,a2,b2,最后的结果为(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"
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,779评论 0 33
  • 一路走,一路花开次第,朋友的数量从来不和年纪成正比。有些朋友,我们走着走着就弄丢了。寂寞的时候,一支烟,一盏暖胃的...
    风也醉人阅读 255评论 0 0
  • 出自:http://www.xiaoboswift.com/course/54
    jetgege阅读 189评论 0 0
  • 2016年5月24号国道102上,一个穿着黑色上衣,及膝黑红格子相间的短裙的女孩,右手擦着双眼不住流出的泪,左手向...
    小胡涂神儿阅读 233评论 0 0
  • 儿子放学以后,经常要求我带他去广场。一到广场上,他就像脱缰的小野马一样,不知疲倦的到处跑,把广场上的健身器材挨个试...
    夏烟阅读 193评论 0 0