您的位置:首页 > 理论基础

leetcode -- 537. Complex Number Multiplication【字符串解析 + 复数相乘计算机实现】

2017-06-29 15:14 405 查看

题目

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.

题意

给定两个字符串表示两个复数,返回字符串表示他们的乘积。

分析及解答

【字符串处理】分割字符串,字符串转整型,字符串拼接。
【运算规则】了解复数的运算规则,通过计算机实现。

public class Solution {
public String complexNumberMultiply(String a, String b) {
int realA = 0,realB = 0;
int imagineA = 0,imagineB = 0;
String arrayA[] = a.split("\\+");
String arrayB[] = b.split("\\+");
realA = Integer.parseInt(arrayA[0]);
realB = Integer.parseInt(arrayB[0]);
imagineA = Integer.parseInt(arrayA[1].substring(0, arrayA[1].indexOf('i')));
imagineB = Integer.parseInt(arrayB[1].substring(0, arrayB[1].indexOf('i')));

int newReal = realA * realB - imagineA * imagineB;
int newImagine = realA * imagineB + realB * imagineA;
StringBuilder result = new StringBuilder();
result.append(newReal).append("+").append(newImagine).append('i');

return result.toString();

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string leetcode
相关文章推荐