diff --git a/src/main/java/com/thealgorithms/bitmanipulation/IsPowerFour.java b/src/main/java/com/thealgorithms/bitmanipulation/IsPowerFour.java new file mode 100644 index 000000000000..54183673dc06 --- /dev/null +++ b/src/main/java/com/thealgorithms/bitmanipulation/IsPowerFour.java @@ -0,0 +1,29 @@ +package com.thealgorithms.bitmanipulation; + +/** + * Utility class for checking if a number is a power of four. + * A power of four is a number that can be expressed as 4^n where n is a non-negative integer. + * This class provides a method to determine if a given integer is a power of four using bit manipulation. + */ +public final class IsPowerFour { + private IsPowerFour() { + } + + /** + * Checks if the given integer is a power of four. + *
+ * A number is considered a power of four if:
+ * - It is greater than zero
+ * - It is a power of two i.e. (n & (n - 1)) == 0
+ * - Its single set bit is in an even position — verified by (n & 0xAAAAAAAA) == 0
+ *
+ * @param number the integer to check
+ * @return true if the number is a power of false, false otherwise
+ */
+ public static boolean isPowerFour(int number) {
+ if (number <= 0) {
+ return false;
+ }
+ return (number & (number - 1)) == 0 && (number & 0xAAAAAAAA) == 0;
+ }
+}
diff --git a/src/test/java/com/thealgorithms/bitmanipulation/IsPowerFourTest.java b/src/test/java/com/thealgorithms/bitmanipulation/IsPowerFourTest.java
new file mode 100644
index 000000000000..4278a7d85632
--- /dev/null
+++ b/src/test/java/com/thealgorithms/bitmanipulation/IsPowerFourTest.java
@@ -0,0 +1,45 @@
+package com.thealgorithms.bitmanipulation;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.stream.Stream;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+/**
+ * Test case for IsPowerFour class
+ */
+
+public class IsPowerFourTest {
+
+ @ParameterizedTest
+ @MethodSource("provideNumbersForPowerFour")
+ public void testIsPowerFour(int number, boolean expected) {
+ if (expected) {
+ assertTrue(IsPowerFour.isPowerFour(number));
+ } else {
+ assertFalse(IsPowerFour.isPowerFour(number));
+ }
+ }
+
+ private static Stream