From b61faf4ede146998892e8582f81ff2290a0836fd Mon Sep 17 00:00:00 2001 From: Bama Charan Chhandogi Date: Fri, 18 Aug 2023 18:23:09 +0530 Subject: [PATCH] Is power two algo added. (#4321) * is power two algo added * Linter solved * Update src/main/java/com/thealgorithms/bitmanipulation/IsPowerTwo.java * Update src/test/java/com/thealgorithms/bitmanipulation/IsPowerTwoTest.java --------- Co-authored-by: BamaCharanChhandogi Co-authored-by: Debasish Biswas --- .../bitmanipulation/IsPowerTwo.java | 16 +++++++++ .../bitmanipulation/IsPowerTwoTest.java | 34 +++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 src/main/java/com/thealgorithms/bitmanipulation/IsPowerTwo.java create mode 100644 src/test/java/com/thealgorithms/bitmanipulation/IsPowerTwoTest.java 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 00000000..d379cb3f --- /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 00000000..69546198 --- /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)); + } +}