ComplexNumberMultiplication [source code]
public class ComplexNumberMultiplication {
static
/******************************************************************************/
public class Solution {
public String complexNumberMultiply(String a, String b) {
int[] operands1 = parse(a), operands2 = parse(b);
int a1 = operands1[0], b1 = operands1[1], a2 = operands2[0], b2 = operands2[1];
int re = a1 * a2 - b1 * b2;
int im = a1 * b2 + a2 * b1;
return re + "+" + im + "i";
}
public int[] parse(String s) {
int[] res = new int[2];
int idxPlus = s.indexOf("+");
int idxI = s.indexOf("i");
res[0] = Integer.parseInt(s.substring(0, idxPlus));
res[1] = Integer.parseInt(s.substring(idxPlus + 1, idxI));
return res;
}
}
/******************************************************************************/
public static void main(String[] args) {
ComplexNumberMultiplication.Solution tester = new ComplexNumberMultiplication.Solution();
String[] inputs = {
"1+1i", "1+1i", "0+2i",
"1+-1i", "1+-1i", "0+-2i",
};
for (int i = 0; i < inputs.length / 3; i++) {
String a = inputs[3 * i];
String b = inputs[1 + 3 * i];
String expected = inputs[2 + 3 * i];
System.out.println(Printer.seperator());
String output = tester.complexNumberMultiply(a, b);
System.out.println(Printer.wrapColor(a + " AND " + b, "magenta") + " -> " + output + Printer.wrapColor(", expected: " + expected, output.equals(expected) ? "green" : "red"));
}
}
}
以后看答案的顺序按照: editorial -> discussion -> submission;
这个题目总体是非常简单的, parse一下直接算就行了.
最后的速度是7ms (55%), 所以估计应该有其他更好的办法;
这个是editorial1, 跟我的是一个思路, 不过稍微短了一些:
public class Solution {
public String complexNumberMultiply(String a, String b) {
String x[] = a.split("\\+|i");
String y[] = b.split("\\+|i");
int a_real = Integer.parseInt(x[0]);
int a_img = Integer.parseInt(x[1]);
int b_real = Integer.parseInt(y[0]);
int b_img = Integer.parseInt(y[1]);
return (a_real * b_real - a_img * b_img) + "+" + (a_real * b_img + a_img * b_real) + "i";
}
}
然后就没了, 毕竟是一个简单的题目;
discussion里面也没有什么更好的解法, 无非就是用stream让代码更短的东西;
submission大部分也就是这个算法了, 无非就是合在一起写的更短; 我目前这个SRP的思路(single responsibility)我感觉还是受用的, 不用为了让代码更短去改;
Problem Description
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.
Difficulty:Medium
Total Accepted:11.2K
Total Submissions:17.3K
Contributor: love_Fawn
Companies
amazon
Related Topics
math string