537. Complex Number Multiplication(C++)

来源:互联网 发布:易建联cba数据 编辑:程序博客网 时间:2024/06/06 14:09

原題

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.


解題思路

使用+和i劃分複數數字區域,把字符串轉為數字,進行運算


代碼

#include <sstream>
#include <stdlib.h>




using namespace std;


class Solution {
public:
    string complexNumberMultiply(string a, string b) {
        int A, B, C, D, E, F;
        string result = "";
        
        A = atoi(a.substr(0,a.find('+')).c_str());
        B = atoi(a.substr(a.find('+')+1,a.find('i')).c_str());
        C = atoi(b.substr(0,b.find('+')).c_str());
        D = atoi(b.substr(b.find('+')+1,b.find('i')).c_str());
        
        E = (A*C - B*D);
        F = (A*D + B*C);
       
        stringstream ss1, ss2;
        string E_str, F_str;
        ss1 << E;
        ss1 >> E_str;
        ss2 << F;
        ss2 >> F_str;
 
        result += E_str;
        result += "+";
        result += F_str;
        result += "i";
        
        return result;
    }
};



感想

想着考試拿C++去做,所以還是換回用C++寫好了。streamstring不知道為甚麼不能用兩次,轉換要使用不同的ss才可以,我不知道這個卡了我一些時間……

原创粉丝点击