Skip to content

Commit f58388c

Browse files
committed
Add Power of Four Check (Bit Manipulation)
1 parent 40561cf commit f58388c

2 files changed

Lines changed: 75 additions & 0 deletions

File tree

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/*
2+
* TheAlgorithms (https://github.com/TheAlgorithms/Java)
3+
* Author: Shewale41
4+
* This file is licensed under the MIT License.
5+
*/
6+
7+
package com.thealgorithms.bitmanipulation;
8+
9+
/**
10+
* Check if a given integer is a power of four using bit manipulation.
11+
*
12+
* <p>A number is a power of four if:
13+
* <ul>
14+
* <li>It is positive.</li>
15+
* <li>It has only one set bit in its binary representation.</li>
16+
* <li>The only set bit is in an even position (checked with 0xAAAAAAAA mask).</li>
17+
* </ul>
18+
*
19+
* <p>Example:
20+
* 4 -> true (2^2)
21+
* 16 -> true (4^2)
22+
* 8 -> false (not power of 4)
23+
*/
24+
public final class PowerOfFour {
25+
26+
private PowerOfFour() {
27+
// Utility class
28+
}
29+
30+
/**
31+
* Checks whether a given integer is a power of four.
32+
*
33+
* @param n number to check
34+
* @return true if n is a power of four, false otherwise
35+
*/
36+
public static boolean isPowerOfFour(int n) {
37+
return n > 0 && (n & (n - 1)) == 0 && (n & 0xAAAAAAAA) == 0;
38+
}
39+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/*
2+
* TheAlgorithms (https://github.com/TheAlgorithms/Java)
3+
* Author: Shewale41
4+
* This file is licensed under the MIT License.
5+
*/
6+
7+
package com.thealgorithms.bitmanipulation;
8+
9+
import static org.junit.jupiter.api.Assertions.assertFalse;
10+
import static org.junit.jupiter.api.Assertions.assertTrue;
11+
12+
import org.junit.jupiter.api.Test;
13+
14+
/**
15+
* Unit tests for {@link PowerOfFour}.
16+
*/
17+
public class PowerOfFourTest {
18+
19+
@Test
20+
void testPowerOfFourTrueCases() {
21+
assertTrue(PowerOfFour.isPowerOfFour(1));
22+
assertTrue(PowerOfFour.isPowerOfFour(4));
23+
assertTrue(PowerOfFour.isPowerOfFour(16));
24+
assertTrue(PowerOfFour.isPowerOfFour(64));
25+
assertTrue(PowerOfFour.isPowerOfFour(256));
26+
}
27+
28+
@Test
29+
void testPowerOfFourFalseCases() {
30+
assertFalse(PowerOfFour.isPowerOfFour(0));
31+
assertFalse(PowerOfFour.isPowerOfFour(2));
32+
assertFalse(PowerOfFour.isPowerOfFour(8));
33+
assertFalse(PowerOfFour.isPowerOfFour(12));
34+
assertFalse(PowerOfFour.isPowerOfFour(-4));
35+
}
36+
}

0 commit comments

Comments
 (0)