Skip to content

Commit b61faf4

Browse files
BamaCharanChhandogiBamaCharanChhandogidebasishbsws
authored
Is power two algo added. (TheAlgorithms#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>
1 parent 68fdec5 commit b61faf4

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package com.thealgorithms.bitmanipulation;
2+
3+
/**
4+
* Is number power of 2
5+
* @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
6+
*/
7+
8+
public class IsPowerTwo {
9+
public static boolean isPowerTwo(int number) {
10+
if (number <= 0) {
11+
return false;
12+
}
13+
int ans = number & (number - 1);
14+
return ans == 0;
15+
}
16+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.thealgorithms.bitmanipulation;
2+
3+
import static org.junit.jupiter.api.Assertions.*;
4+
5+
import org.junit.jupiter.api.Test;
6+
7+
/**
8+
* Test case for IsPowerTwo class
9+
* @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
10+
*/
11+
12+
public class IsPowerTwoTest {
13+
@Test
14+
public void testIsPowerTwo() {
15+
// test some positive powers of 2
16+
assertTrue(IsPowerTwo.isPowerTwo(1));
17+
assertTrue(IsPowerTwo.isPowerTwo(2));
18+
assertTrue(IsPowerTwo.isPowerTwo(4));
19+
assertTrue(IsPowerTwo.isPowerTwo(16));
20+
assertTrue(IsPowerTwo.isPowerTwo(1024));
21+
22+
// test some negative numbers
23+
assertFalse(IsPowerTwo.isPowerTwo(-1));
24+
assertFalse(IsPowerTwo.isPowerTwo(-2));
25+
assertFalse(IsPowerTwo.isPowerTwo(-4));
26+
27+
// test some numbers that are not powers of 2
28+
assertFalse(IsPowerTwo.isPowerTwo(0));
29+
assertFalse(IsPowerTwo.isPowerTwo(3));
30+
assertFalse(IsPowerTwo.isPowerTwo(5));
31+
assertFalse(IsPowerTwo.isPowerTwo(15));
32+
assertFalse(IsPowerTwo.isPowerTwo(1000));
33+
}
34+
}

0 commit comments

Comments
 (0)