Skip to content

Commit db1f33e

Browse files
committed
Added PowerOfFour algorithm in bitmanipulation
1 parent bb6385e commit db1f33e

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package bitmanipulation;
2+
3+
public class PowerOfFour {
4+
public static boolean isPowerOfFour(int n) {
5+
// A power of 4 has only one bit set and that bit is at an even position
6+
return n > 0 && (n & (n - 1)) == 0 && (n & 0x55555555) != 0;
7+
}
8+
9+
public static void main(String[] args) {
10+
int num = 64; // change to test other numbers
11+
if (isPowerOfFour(num))
12+
System.out.println(num + " is a power of 4.");
13+
else
14+
System.out.println(num + " is NOT a power of 4.");
15+
}
16+
}

0 commit comments

Comments
 (0)