forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathComplexNumberMultiply.java
More file actions
35 lines (28 loc) · 900 Bytes
/
ComplexNumberMultiply.java
File metadata and controls
35 lines (28 loc) · 900 Bytes
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
33
34
35
package com.thealgorithms.strings;
/**
* Multiplies two complex numbers represented as strings in the form "a+bi".
*
* Example:
* Input: 1+1i , 1+1i
* Output: 0+2i
*/
public final class ComplexNumberMultiply {
private ComplexNumberMultiply() {
}
private static int[] parse(String num) {
String[] parts = num.split("\\+");
int real = Integer.parseInt(parts[0]);
int imaginary = Integer.parseInt(parts[1].replace("i", ""));
return new int[] {real, imaginary};
}
public static String multiply(String num1, String num2) {
int[] a = parse(num1);
int[] b = parse(num2);
int real = a[0] * b[0] - a[1] * b[1];
int imaginary = a[0] * b[1] + a[1] * b[0];
return real + "+" + imaginary + "i";
}
public static void main(String[] args) {
System.out.println(multiply("1+1i", "1+1i"));
}
}