mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-08 02:04:31 +08:00
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 <b.c.chhandogi@gmailcom> Co-authored-by: Debasish Biswas <debasishbsws.dev@gmail.com>
This commit is contained in:

committed by
GitHub

parent
68fdec5977
commit
b61faf4ede
@ -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;
|
||||||
|
}
|
||||||
|
}
|
@ -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));
|
||||||
|
}
|
||||||
|
}
|
Reference in New Issue
Block a user