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:
- The input strings will not have extra blank.
- 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"; } };
參考資料:
https://discuss.leetcode.com/topic/84261/java-3-liner
https://discuss.leetcode.com/topic/84382/c-using-stringstream
https://discuss.leetcode.com/topic/84323/java-elegant-solution
https://discuss.leetcode.com/topic/84508/cpp-solution-with-sscanf