版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21275321/article/details/84108103
题目:
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:
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.
解释:
实现复数乘法。明白了复数的乘法的计算过程后,其实就是字符串解析问题了。
python代码:
class Solution(object):
def complexNumberMultiply(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
a1,a2=map(int,a[:-1].split('+'))
b1,b2=map(int,b[:-1].split('+'))
return '%d+%di'%(a1*b1-a2*b2,a2*b1+b2*a1)
c++代码:
#include<sstream>
#include<cstdlib>
using namespace std;
class Solution {
public:
string complexNumberMultiply(string a, string b) {
a=a.substr(0,a.size()-1);
b=b.substr(0,b.size()-1);
istringstream aa(a);
istringstream bb(b);
vector<int> a_list;
vector<int> b_list;
string word;
while(getline(aa,word,'+'))
{
a_list.push_back(atoi(word.c_str()));
}
while(getline(bb,word,'+'))
{
b_list.push_back(atoi(word.c_str()));
}
int res_n=a_list[0]*b_list[0]-a_list[1]*b_list[1];
int res_i=a_list[0]*b_list[1]+a_list[1]*b_list[0];
return to_string(res_n)+"+"+to_string(res_i)+"i";
}
};
总结: