Skip to content

Commit 3531ea1

Browse files
committed
fix: handle negative inputs
1 parent 7eb4d88 commit 3531ea1

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

src/main/java/com/thealgorithms/maths/GenericRoot.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@ public static void main(String[] args) {
1616
}
1717

1818
public static int genericRoot(int n) {
19+
if (n < 0) {
20+
return genericRoot(-n);
21+
}
1922
int root = 0;
2023
while (n > 0 || root > 9) {
2124
if (n == 0) {

src/test/java/com/thealgorithms/maths/GenericRootTest.java

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,18 @@
77
import org.junit.jupiter.api.Test;
88

99
public class GenericRootTest {
10+
private final Map<Integer, Integer> testCases = Map.ofEntries(entry(0, 0), entry(1, 1), entry(12345, 6), entry(123, 6), entry(15937, 7), entry(222222, 3), entry(99999, 9));
1011
@Test
1112
public void testGenericRoot() {
12-
final Map<Integer, Integer> testCases = Map.ofEntries(entry(0, 0), entry(1, 1), entry(12345, 6), entry(123, 6), entry(15937, 7), entry(222222, 3), entry(99999, 9));
1313
for (final var tc : testCases.entrySet()) {
1414
assertEquals(tc.getValue(), GenericRoot.genericRoot(tc.getKey()));
1515
}
1616
}
17-
}
17+
18+
@Test
19+
public void testGenericRootWithNegativeInputs() {
20+
for (final var tc : testCases.entrySet()) {
21+
assertEquals(tc.getValue(), GenericRoot.genericRoot(-tc.getKey()));
22+
}
23+
}
24+
}

0 commit comments

Comments
 (0)