Given an integer n, return true if it is a power of four. Otherwise, return false.
An integer n is a power of four, if there exists an integer x such that n == 4x.
Example 1:
Input: n = 16
Output: true
Example 2:
Input: n = 5
Output: false
Example 3:
Input: n = 1
Output: true
Constraints:
-231 <= n <= 231 - 1
Problem statement to practice: https://leetcode.com/problems/power-of-four/
Solution:
Firstly, no negative number could be the power of 4
Think of a number you want to check,
n = 16 -> you see it could be represented as 4 * 4
and not for n = 5
So when we have divisible by 4 till the point we receive 1, we can say that the number is in power of 4.
The apt way to do this with respect to power of 2 is the convert the number to binary and check for a single set bit.
The same applies to power of 4, ie, convert the number to power of 4. Post which check if only a single bit is active.
To check the only set bit, just sum the bits, the sum we received is number of set bit's
Show me the single liner code
class Solution {
public boolean isPowerOfFour(int n) {
return n > 0
&& Integer.toString(n, 4)
.chars()
.map(ch -> ch - '0')
.sum() == 1;
}
}
Top comments (0)