![]() |
VOOZH | about |
Given an integer n, find whether it is a power of 4 or not.
Example :
Input : n = 16
Output : true
Explanation: 16 is a power of 4
Input : 20
Output : false
Explanation: 20 is not a power of 4
Table of Content
The idea is to first check whether the number is a power of 2 (i.e., it has only one set bit), and then ensure that the position of this set bit is at an even index (counting from 0), which guarantees it is a power of 4. This can be verified using bit operations by confirming that n & (n - 1) == 0 and the set bit lies at an even position.
True
Explanation: The binary representation of 64 is 1000000, which has only one set bit, so it is a power of 2. The position of this set bit (counting from 0) is 6, which is an even index. Since both conditions are satisfied, the number 64 is a power of 4.
If a number n is a power of 4, then log₄(n) will always be an integer. So, we compute log₄(n) and check whether its floor value is equal to its ceil value; if both are equal, it means the value is an integer and hence n is a power of 4.
True
Explanation: For n = 64, we compute log base 4 of 64, which gives 3. Since this value is an integer, its floor and ceil values are equal. Hence, 64 is a power of 4.
The idea is to first check whether the number has only one set bit (i.e., it is a power of 2 using n & (n - 1) == 0). Then, we ensure that this set bit is not in any odd position by verifying that n & 0xAAAAAAAA == 0, since this mask has all bits set at odd positions. If both conditions are satisfied, the number is a power of 4.
True
Note: A number can be identified as a power of 4 if it has only one set bit (i.e., it is a power of 2) and the number of trailing zeros is even. Using built-in functions like "__builtin_ctz(n)" in C++ or "Integer.numberOfTrailingZeros(n)" in Java, this condition can be checked efficiently in a single line.
A number is a power of 4 if it is first a power of 2 (only one set bit), and additionally satisfies n % 3 == 1, since all powers of 4 leave a remainder of 1 when divided by 3.
True
Explanation: First, we check whether 64 is a power of 2. The binary representation of 64 is 1000000, which has only one set bit, so it satisfies this condition. Next, we check the modulo condition: 64 % 3 = 1. Since both conditions are satisfied so 64 is a power of 4.