LeetCode - Algorithms - 537. Complex Number Multiplication

Problem

537. Complex Number Multiplication

Java

Complex.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
public String complexNumberMultiply(String a, String b) {
int re1 = Integer.parseInt(a.substring(0, a.indexOf("+")));
int im1 = Integer.parseInt(a.substring(a.indexOf("+") + 1, a.length() - 1));
Complex c1 = new Complex(re1, im1);
int re2 = Integer.parseInt(b.substring(0, b.indexOf("+")));
int im2 = Integer.parseInt(b.substring(b.indexOf("+") + 1, b.length() - 1));
Complex c2 = new Complex(re2, im2);
Complex c = c1.times(c2);
return c.toString();
}
}

class Complex {
private int re;
private int im;

public Complex(int real, int imag) {
this.re = real;
this.im = imag;
}

public String toString() {
return re + "+" + im + "i";
}

public Complex times(Complex that) {
int real = this.re * that.re - this.im * that.im;
int imag = this.re * that.im + this.im * that.re;
return new Complex(real, imag);
}
}

Submission Detail

  • 55 / 55 test cases passed.
  • Runtime: 4 ms, faster than 81.21% of Java online submissions for Complex Number Multiplication.
  • Memory Usage: 37.6 MB, less than 17.58% of Java online submissions for Complex Number Multiplication.