1. 程式人生 > >[LeetCode] Complex Number Multiplication 複數相乘

[LeetCode] 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 + i

2

 + 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 + i

2

 - 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
    .

這道題讓我們求複數的乘法,有關複數的知識最早還是在本科的複變函式中接觸到的,難起來還真是難。但是這裡只是最簡單的乘法,只要利用好定義i2=-1就可以解題,而且這道題的另一個考察點其實是對字元的處理,我們需要把字串中的實部和虛部分離開並進行運算,那麼我們可以用STL中自帶的find_last_of函式來找到加號的位置,然後分別拆出實部虛部,進行運算後再變回字串,參見程式碼如下:

解法一:

class Solution {
public:
    string complexNumberMultiply(string a, string b) {
        int
n1 = a.size(), n2 = b.size(); auto p1 = a.find_last_of("+"), p2 = b.find_last_of("+"); int a1 = stoi(a.substr(0, p1)), b1 = stoi(b.substr(0, p2)); int a2 = stoi(a.substr(p1 + 1, n1 - p1 - 2)); int b2 = stoi(b.substr(p2 + 1, n2 - p2 - 2)); int r1 = a1 * b1 - a2 * b2, r2 = a1 * b2 + a2 * b1; return to_string(r1) + "+" + to_string(r2) + "i"; } };

下面這種方法利用到了字串流類istringstream來讀入字串,直接將實部虛部讀入int變數中,注意中間也要把加號讀入char變數中,然後再進行運算即可,參見程式碼如下:

解法二:

class Solution {
public:
    string complexNumberMultiply(string a, string b) {
        istringstream is1(a), is2(b);
        int a1, a2, b1, b2, r1, r2;
        char plus;
        is1 >> a1 >> plus >> a2;
        is2 >> b1 >> plus >> b2;
        r1 = a1 * b1 - a2 * b2, r2 = a1 * b2 + a2 * b1;
        return to_string(r1) + "+" + to_string(r2) + "i";
    }
};

下面這種解法實際上是C語言的解法,用到了sscanf這個讀入字串的函式,需要把string轉為cost char*型,然後標明讀入的方式和型別,再進行運算即可,參見程式碼如下:

解法三:

class Solution {
public:
    string complexNumberMultiply(string a, string b) {
        int a1, a2, b1, b2, r1, r2;
        sscanf(a.c_str(), "%d+%di", &a1, &a2);
        sscanf(b.c_str(), "%d+%di", &b1, &b2);
        r1 = a1 * b1 - a2 * b2, r2 = a1 * b2 + a2 * b1;
        return to_string(r1) + "+" + to_string(r2) + "i";
    }
};

參考資料: