题目地址:https://leetcode.com/problems/complex-number-multiplication/description/

题目描述

Given two strings representing two complex numbers.

Youneed 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、 Theinputstringswillnothaveextrablank.;
2、 Theinputstringswillbegivenintheformofa+bi,wheretheintegeraandbwillbothbelongtotherangeof[-100,100].Andtheoutputshouldbealsointhisform.;

解题方法

方法一:

求两个复数的乘积。这个题中已经说明了一定会存在+号,这就是留个我们根据格式化的表达读取数字的实虚部用的。

另外,注意字符串的格式化时,后面所有的变量必须用括号括起来才行,也就是tuple型。

class Solution(object):
    def complexNumberMultiply(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        num1 = map(int, a[:-1].split('+'))
        num2 = map(int, b[:-1].split('+'))
        real = num1[0] * num2[0] - num1[1] * num2[1]
        virtual = num1[0] * num2[1] + num1[1] * num2[0]
        return "%d+%di" % (real, virtual)

1 2 3 4 5 6 7 8 9 10 11 12

C++处理的字符串的时候稍微麻烦了一些。

class Solution {
public:
    string complexNumberMultiply(string a, string b) {
        int ap = a.find('+');
        int ar = stoi(a.substr(0, ap));
        int ai = stoi(a.substr(ap + 1, a.size() - 1));
        int bp = b.find('+');
        int br = stoi(b.substr(0, bp));
        int bi = stoi(b.substr(bp + 1, b.size() - 1));
        string ansr = to_string(ar * br - ai * bi);
        string ansi = to_string(ar * bi + ai * br);
        return ansr + '+' + ansi + 'i';
    }
};

1 2 3 4 5 6 7 8 9 10 11 12 13 14

DDKK.COM 弟弟快看-教程,程序员编程资料站,版权归原作者所有

本文经作者:负雪明烛 授权发布,任何组织或个人未经作者授权不得转发