File tree Expand file tree Collapse file tree
main/java/com/thealgorithms/bitmanipulation
test/java/com/thealgorithms/bitmanipulation Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments