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
32 lines (25 loc) · 958 Bytes
/
ComplexNumberMultiply.java
File metadata and controls
32 lines (25 loc) · 958 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
package com.thealgorithms.maths;
/**
* Multiplies two complex numbers represented as strings in the form "a+bi".
* Supports negative values and validates input format.
*/
public final class ComplexNumberMultiply {
private ComplexNumberMultiply() {
}
private static int[] parse(String num) {
if (num == null || !num.matches("-?\\d+\\+-?\\d+i")) {
throw new IllegalArgumentException("Invalid complex number format: " + 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";
}
}