Skip to content
Open
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.thealgorithms.bitmanipulation;

/**
* This class provides a method to check if a given number is a power of four.
*/
public final class PowerOfFour {

/** Private constructor to prevent instantiation. */
private PowerOfFour() {
throw new AssertionError("Cannot instantiate utility class.");
}

/**
* Checks whether the given integer is a power of four.
*
* @param n the number to check
* @return true if n is a power of four, false otherwise
*/
public static boolean isPowerOfFour(int n) {
if (n <= 0) {
return false;
} else {
return (n & (n - 1)) == 0 && (n & 0x55555555) != 0;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.thealgorithms.bitmanipulation;

/**
* This class provides a method to check if a given number is a power of four.
*/
public final class PowerOfFour {

// Private constructor to prevent instantiation
private PowerOfFour() {
throw new AssertionError("Cannot instantiate utility class");
}

/**
* Checks whether the given integer is a power of four.
*
* @param n the number to check
* @return true if n is a power of four, false otherwise
*/
public static boolean isPowerOfFour(int n) {
if (n <= 0) {
return false;
} else {
return (n & (n - 1)) == 0 && (n & 0x55555555) != 0;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.thealgorithms.bitmanipulation;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

/**
* Unit tests for {@link PowerOfFour}.
*/
public final class PowerOfFourTest {

@Test
void testPowerOfFourTrueCases() {
Assertions.assertTrue(PowerOfFour.isPowerOfFour(1));
Assertions.assertTrue(PowerOfFour.isPowerOfFour(4));
Assertions.assertTrue(PowerOfFour.isPowerOfFour(16));
Assertions.assertTrue(PowerOfFour.isPowerOfFour(64));
}

@Test
void testPowerOfFourFalseCases() {
Assertions.assertFalse(PowerOfFour.isPowerOfFour(0));
Assertions.assertFalse(PowerOfFour.isPowerOfFour(2));
Assertions.assertFalse(PowerOfFour.isPowerOfFour(8));
Assertions.assertFalse(PowerOfFour.isPowerOfFour(12));
}

@Test
void testNegativeNumbers() {
Assertions.assertFalse(PowerOfFour.isPowerOfFour(-4));
Assertions.assertFalse(PowerOfFour.isPowerOfFour(-16));
}
}