Skip to content

tests: add PowerOfTwoOrNotTest #4279

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Aug 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 3 additions & 9 deletions src/main/java/com/thealgorithms/maths/PowerOfTwoOrNot.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,8 @@
* A utility to check if a given number is power of two or not. For example 8,16
* etc.
*/
public class PowerOfTwoOrNot {

public static void main(String[] args) {
assert !checkIfPowerOfTwoOrNot(0);
assert checkIfPowerOfTwoOrNot(1);
assert checkIfPowerOfTwoOrNot(8);
assert checkIfPowerOfTwoOrNot(16);
assert checkIfPowerOfTwoOrNot(1024);
public final class PowerOfTwoOrNot {
private PowerOfTwoOrNot() {
}

/**
Expand All @@ -21,7 +15,7 @@ public static void main(String[] args) {
* @return {@code true} if given number is power of two, otherwise
* {@code false}
*/
public static boolean checkIfPowerOfTwoOrNot(int number) {
public static boolean checkIfPowerOfTwoOrNot(final int number) {
return number != 0 && ((number & (number - 1)) == 0);
}
}
25 changes: 25 additions & 0 deletions src/test/java/com/thealgorithms/maths/PowerOfTwoOrNotTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.thealgorithms.maths;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.util.Map;
import org.junit.jupiter.api.Test;

public class PowerOfTwoOrNotTest {
@Test
public void testPowerOfTwoOrNotForPowersOfTwo() {
final var powersOfTwo = new int[] {1, 2, 4, 8, 16, 32, 64};
for (final var n : powersOfTwo) {
assertTrue(PowerOfTwoOrNot.checkIfPowerOfTwoOrNot(n));
}
}

@Test
public void testPowerOfTwoOrNotForNotPowersOfTwo() {
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};
for (final var n : notPowersOfTwo) {
assertFalse(PowerOfTwoOrNot.checkIfPowerOfTwoOrNot(n));
}
}
}