1. 程式人生 > >Leetcode 537. Complex Number Multiplication

Leetcode 537. Complex Number Multiplication

題意

  • 就是兩個複數以字串形式輸入,計算相加結果

思路

  • 思路很簡單,就是用+號切字串,再算就行了
  • 記下來的原因,主要是記錄下string split的函式,以後方便找

實現

class Solution {
public:
    void split(string& s, vector<string>& res, const string& c){
        string::size_type pos1 = 0, pos2 = s.find(c);
        while (pos2 != string
::npos){ res.push_back(s.substr(pos1, pos2 - pos1)); pos1 = pos2 + c.length(); pos2 = s.find(c, pos1); } if (pos1 < s.length()) res.push_back(s.substr(pos1, pos2 - pos1)); } string complexNumberMultiply(string a, string b) { a = a.substr(0
, a.length() - 1); b = b.substr(0, b.length() - 1); vector<string> as, bs; split(a, as, "+"); split(b, bs, "+"); int x, y; x = stoi(as[0]) * stoi(bs[0]) - stoi(as[1]) * stoi(bs[1]); y = stoi(as[0]) * stoi(bs[1]) + stoi(as[1]) * stoi(bs[0]); return
to_string(x) + "+" + to_string(y) + "i"; } };