forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPowerOfFour.java
More file actions
39 lines (35 loc) · 981 Bytes
/
PowerOfFour.java
File metadata and controls
39 lines (35 loc) · 981 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/*
* TheAlgorithms (https://github.com/TheAlgorithms/Java)
* Author: Shewale41
* This file is licensed under the MIT License.
*/
package com.thealgorithms.bitmanipulation;
/**
* Check if a given integer is a power of four using bit manipulation.
*
* <p>A number is a power of four if:
* <ul>
* <li>It is positive.</li>
* <li>It has only one set bit in its binary representation.</li>
* <li>The only set bit is in an even position (checked with 0xAAAAAAAA mask).</li>
* </ul>
*
* <p>Example:
* 4 -> true (2^2)
* 16 -> true (4^2)
* 8 -> false (not power of 4)
*/
public final class PowerOfFour {
private PowerOfFour() {
// Utility class
}
/**
* Checks whether a given integer is a power of four.
*
* @param n number to check
* @return true if n is a power of four, false otherwise
*/
public static boolean isPowerOfFour(int n) {
return n > 0 && (n & (n - 1)) == 0 && (n & 0xAAAAAAAA) == 0;
}
}