Problem: Given an integer num, return true if it is a power of four. Otherwise, return false.
Example:
Input: num = 64 Output: true
Approach: Here are the points which we need to focus:
- if input number is 0, it is not power of 4 (obviously).
- Any number which is a power of 4 will definitely be a power of 2.
- We know that num is power of 2 if if num & (nums - 1) is 0.
- Every number which is power of 2, is a power of 4 if num - 1 is divisible by 3. You can see this by examples or you can look at the proof by induction here.
If you understood the above points. Solution can be easily understood by just looking at the implementation.
Implementation:
public bool IsPowerOfFour(int num)
{
return num > 0 && (num & (num - 1)) == 0 && (num - 1) % 3 == 0;
}
Complexity: O(1)
No comments:
Post a Comment