diff --git a/src/main/java/com/thealgorithms/bitmanipulation/IsPowerTwo.java b/src/main/java/com/thealgorithms/bitmanipulation/IsPowerTwo.java new file mode 100644 index 000000000..d379cb3f0 --- /dev/null +++ b/src/main/java/com/thealgorithms/bitmanipulation/IsPowerTwo.java @@ -0,0 +1,16 @@ +package com.thealgorithms.bitmanipulation; + +/** + * Is number power of 2 + * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) + */ + +public class IsPowerTwo { + public static boolean isPowerTwo(int number) { + if (number <= 0) { + return false; + } + int ans = number & (number - 1); + return ans == 0; + } +} diff --git a/src/test/java/com/thealgorithms/bitmanipulation/IsPowerTwoTest.java b/src/test/java/com/thealgorithms/bitmanipulation/IsPowerTwoTest.java new file mode 100644 index 000000000..695461980 --- /dev/null +++ b/src/test/java/com/thealgorithms/bitmanipulation/IsPowerTwoTest.java @@ -0,0 +1,34 @@ +package com.thealgorithms.bitmanipulation; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; + +/** + * Test case for IsPowerTwo class + * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) + */ + +public class IsPowerTwoTest { + @Test + public void testIsPowerTwo() { + // test some positive powers of 2 + assertTrue(IsPowerTwo.isPowerTwo(1)); + assertTrue(IsPowerTwo.isPowerTwo(2)); + assertTrue(IsPowerTwo.isPowerTwo(4)); + assertTrue(IsPowerTwo.isPowerTwo(16)); + assertTrue(IsPowerTwo.isPowerTwo(1024)); + + // test some negative numbers + assertFalse(IsPowerTwo.isPowerTwo(-1)); + assertFalse(IsPowerTwo.isPowerTwo(-2)); + assertFalse(IsPowerTwo.isPowerTwo(-4)); + + // test some numbers that are not powers of 2 + assertFalse(IsPowerTwo.isPowerTwo(0)); + assertFalse(IsPowerTwo.isPowerTwo(3)); + assertFalse(IsPowerTwo.isPowerTwo(5)); + assertFalse(IsPowerTwo.isPowerTwo(15)); + assertFalse(IsPowerTwo.isPowerTwo(1000)); + } +}