1. 程式人生 > >LeetCode 537. 複數乘法(C++、python)

LeetCode 537. 複數乘法(C++、python)

給定兩個表示複數的字串。

返回表示它們乘積的字串。注意,根據定義 i2 = -1 。

示例 1:

輸入: "1+1i", "1+1i"
輸出: "0+2i"
解釋: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i ,你需要將它轉換為 0+2i 的形式。

示例 2:

輸入: "1+-1i", "1+-1i"
輸出: "0+-2i"
解釋: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i ,你需要將它轉換為 0+-2i 的形式。 

注意:

輸入字串不包含額外的空格。

輸入字串將以 a+bi

 的形式給出,其中整數 a 和 b 的範圍均在 [-100, 100] 之間。輸出也應當符合這種形式

C++

class Solution {
public:
    string complexNumberMultiply(string a, string b) 
    {
        int m=a.length();
        int n=b.length();
        int i=0;
        int idx1;
        int idx2;
        while(i<m)
        {
            if('+'==a[i])
            {
                idx1=i;
                break;
            }
            i++;
        }
        i=0;
        while(i<n)
        {
            if('+'==b[i])
            {
                idx2=i;
                break;
            }
            i++;
        }
        string a0=a.substr(0,idx1);
        string a1=a.substr(idx1+1,m-idx1-1);
        string b0=b.substr(0,idx2);
        string b1=b.substr(idx2+1,n-idx2-1);  
        int A0,A1,B0,B1;
        A0=atoi(a0.c_str());
        A1=atoi(a1.c_str());
        B0=atoi(b0.c_str());
        B1=atoi(b1.c_str());
        int res1=A0*B0-A1*B1;
        int res2=A0*B1+A1*B0;
        string res="";
        res+=to_string(res1)+'+'+to_string(res2)+'i';
        return res;
    }
};

python

class Solution(object):
    def complexNumberMultiply(self, a, b):
        idx1=a.find('+')
        idx2=b.find('+')
        a0=int(a[0:idx1])
        a1=int(a[idx1+1:-1])
        b0=int(b[0:idx2])
        b1=int(b[idx2+1:-1])
        return str(a0*b0-a1*b1)+'+'+str(a0*b1+a1*b0)+'i'