Skip to content

Commit c4a9ef1

Browse files
authored
Add PowerOfTwoOrNotTest (#4279)
1 parent ee23b6c commit c4a9ef1

File tree

2 files changed

+28
-9
lines changed

2 files changed

+28
-9
lines changed

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

+3-9
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,8 @@
44
* A utility to check if a given number is power of two or not. For example 8,16
55
* etc.
66
*/
7-
public class PowerOfTwoOrNot {
8-
9-
public static void main(String[] args) {
10-
assert !checkIfPowerOfTwoOrNot(0);
11-
assert checkIfPowerOfTwoOrNot(1);
12-
assert checkIfPowerOfTwoOrNot(8);
13-
assert checkIfPowerOfTwoOrNot(16);
14-
assert checkIfPowerOfTwoOrNot(1024);
7+
public final class PowerOfTwoOrNot {
8+
private PowerOfTwoOrNot() {
159
}
1610

1711
/**
@@ -21,7 +15,7 @@ public static void main(String[] args) {
2115
* @return {@code true} if given number is power of two, otherwise
2216
* {@code false}
2317
*/
24-
public static boolean checkIfPowerOfTwoOrNot(int number) {
18+
public static boolean checkIfPowerOfTwoOrNot(final int number) {
2519
return number != 0 && ((number & (number - 1)) == 0);
2620
}
2721
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package com.thealgorithms.maths;
2+
3+
import static org.junit.jupiter.api.Assertions.assertFalse;
4+
import static org.junit.jupiter.api.Assertions.assertTrue;
5+
6+
import java.util.Map;
7+
import org.junit.jupiter.api.Test;
8+
9+
public class PowerOfTwoOrNotTest {
10+
@Test
11+
public void testPowerOfTwoOrNotForPowersOfTwo() {
12+
final var powersOfTwo = new int[] {1, 2, 4, 8, 16, 32, 64};
13+
for (final var n : powersOfTwo) {
14+
assertTrue(PowerOfTwoOrNot.checkIfPowerOfTwoOrNot(n));
15+
}
16+
}
17+
18+
@Test
19+
public void testPowerOfTwoOrNotForNotPowersOfTwo() {
20+
final var notPowersOfTwo = new int[] {-16, -8, -6, -5, -4, -3, -2, -1, 0, 3, 5, 6, 7, 9, 10, 11, 33, 63, 65, 1000, 9999};
21+
for (final var n : notPowersOfTwo) {
22+
assertFalse(PowerOfTwoOrNot.checkIfPowerOfTwoOrNot(n));
23+
}
24+
}
25+
}

0 commit comments

Comments
 (0)