【数字字符串互转】【C++】LeetCode#72 537. 复数乘法 Medium
A complex number can be represented as a string on the form "real+imaginaryi" where:
-
real is the real part and is an integer in the range [-100, 100]. -
imaginary is the imaginary part and is an integer in the range [-100, 100]. -
.
Given two complex numbers num1 and num2 as strings, return a string of the complex number that represents their multiplications.
Example 1:
Input: num1 = "1+1i", num2 = "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: num1 = "1+-1i", num2 = "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.
Constraints:
num1 and num2 are valid complex numbers.
复数 可以用字符串表示,遵循 "实部+虚部i" 的形式,并满足下述条件:
-
实部 是一个整数,取值范围是 [-100, 100] -
虚部 也是一个整数,取值范围是 [-100, 100] -
.
给你两个字符串表示的复数 num1 和 num2 ,请你遵循复数表示形式,返回表示它们乘积的字符串。
示例 1:
输入:num1 = "1+1i", num2 = "1+1i"
输出:"0+2i"
解释:(1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i ,你需要将它转换为 0+2i 的形式。
示例 2:
输入:num1 = "1+-1i", num2 = "1+-1i"
输出:"0+-2i"
解释:(1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i ,你需要将它转换为 0+-2i 的形式。
提示:
num1 和 num2 都是有效的复数表示。
「题解」
-
字符串题目 -
复数运算法则:(a+bi)*(c+di)=(ac-bd)+(ad+bc)i -
将num1和num2的实部和虚部用 find()
和stoi()
分别找出来,再进行复数运算,用to_string()
转化为字符串并用'+'拼接
「AC代码」
class Solution {
public:
string complexNumberMultiply(string num1, string num2)
{
int pos1 = num1.find('+'); // 找到第一个加号的位置
int pos2 = num2.find('+');
int a = stoi(num1.substr(0, pos1)), b = stoi(num1.substr(pos1 + 1, num1.size() - pos1 - 2));
// num1.size() - pos1 - 2--num1的虚部的长度:len-1-(pos1+1)
// substr()函数的第二个参数是字符串长度
// stoi()函数将字符串转化为数字
int c = stoi(num2.substr(0, pos2)), d = stoi(num2.substr(pos2 + 1, num2.size() - pos2 - 2));
string ans = to_string(a * c - b * d) + '+' + to_string(a * d + b * c) + 'i';
// to_string()函数将数字转化为字符串
return ans;
}
};