simplified the parsing using regex
This commit is contained in:
parent
aabaaf5ec9
commit
bb499f340c
|
@ -4,6 +4,9 @@ import org.junit.jupiter.api.Assertions;
|
||||||
import org.junit.jupiter.params.ParameterizedTest;
|
import org.junit.jupiter.params.ParameterizedTest;
|
||||||
import org.junit.jupiter.params.provider.CsvSource;
|
import org.junit.jupiter.params.provider.CsvSource;
|
||||||
|
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
class ComplexNumber {
|
class ComplexNumber {
|
||||||
public long real;
|
public long real;
|
||||||
public long imaginary;
|
public long imaginary;
|
||||||
|
@ -13,39 +16,23 @@ class ComplexNumber {
|
||||||
this.imaginary = b;
|
this.imaginary = b;
|
||||||
}
|
}
|
||||||
|
|
||||||
public ComplexNumber(String complexNumberStr1) {
|
public ComplexNumber(String complexNumberStr) {
|
||||||
|
|
||||||
String complexNumberStr = complexNumberStr1.replaceAll("\\s", "");
|
Pattern pattern = Pattern.compile("(-?\\d+)?(?:([+-]?\\d+)i)?");
|
||||||
if (complexNumberStr.contains("i")) {
|
Matcher matcher = pattern.matcher(complexNumberStr.replaceAll("\\s", ""));
|
||||||
// Split the string based on '+' or '-'
|
|
||||||
String[] parts = complexNumberStr.split("(?=[+-])");
|
|
||||||
|
|
||||||
if (parts.length == 1) {
|
if (matcher.matches()) {
|
||||||
// Only real part (no imaginary part)
|
// Extract real and imaginary parts
|
||||||
if (complexNumberStr.endsWith("i")) {
|
String realPartStr = matcher.group(1);
|
||||||
real = 0;
|
String imaginaryPartStr = matcher.group(2);
|
||||||
imaginary = Long.parseLong(parts[0].substring(0, parts[0].length() - 1));
|
|
||||||
|
// Parse real part (if present)
|
||||||
|
real = (realPartStr != null) ? Long.parseLong(realPartStr) : 0;
|
||||||
|
|
||||||
|
// Parse imaginary part (if present)
|
||||||
|
imaginary = (imaginaryPartStr != null) ? Long.parseLong(imaginaryPartStr) : 0;
|
||||||
} else {
|
} else {
|
||||||
real = Long.parseLong(complexNumberStr);
|
throw new IllegalArgumentException("Invalid complex number format, supported format is `a+bi`");
|
||||||
imaginary = 0;
|
|
||||||
}
|
|
||||||
} else if (parts.length == 2) {
|
|
||||||
// Both real and imaginary parts present
|
|
||||||
real = Long.parseLong(parts[0]);
|
|
||||||
String imaginaryString = parts[1].substring(0, parts[1].length() - 1); // Remove 'i'
|
|
||||||
if (imaginaryString.isEmpty()) {
|
|
||||||
// Only 'i' without coefficient, hence imaginary part is 1
|
|
||||||
imaginary = 1;
|
|
||||||
} else {
|
|
||||||
imaginary = Long.parseLong(imaginaryString);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
throw new IllegalArgumentException("Invalid complex number format");
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// Only real part without 'i'
|
|
||||||
real = Long.parseLong(complexNumberStr);
|
|
||||||
imaginary = 0;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue