题目描述:
给定两个表示复数的字符串。
返回表示它们乘积的字符串。注意,根据定义 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] 之间。输出也应当符合这种形式。
解题思路:
本题主要是考查 atoi的用法。
AC代码:
class Solution {
public:
vector<string> split(const string& str, const string& pattern)
{
vector<string> ret;
if (pattern.empty()) return ret;
size_t start = 0, index = str.find_first_of(pattern, 0);
while (index != str.npos)
{
if (start != index)
ret.push_back(str.substr(start, index - start));
start = index + 1;
index = str.find_first_of(pattern, start);
}
if (!str.substr(start).empty())
ret.push_back(str.substr(start));
return ret;
}
string complexNumberMultiply(string a, string b) {
vector<string> vec1 = split(a, "+");
vector<string> vec2 = split(b, "+");
int n1 = atoi(vec1[0].c_str());
int n2 = atoi(vec2[0].c_str());
int m1 = atoi(vec1[1].c_str());
int m2 = atoi(vec2[1].c_str());
int sum1 = n1 * n2 - m1 * m2;
int sum2 = n1 * m2 + n2 * m1;
string res = to_string(sum1) + "+" + to_string(sum2) + "i";
return res;
}
};