Share the joy
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Example:
Given num = 16, return true. Given num = 5, return false.
Solution. This is another good one for bit manipulation.
First of all, any negative number should return false.
2nd, we can use num & (-num) to test if binary form only has one 1. In another word, to see if num is power of 2.
In the end, because power of four only has 1 in odd position:
1
100
10000
1000000
To test if 1 exists at odd position, we need to use num & 0x55555555
The final answer is return (num & (num – 1)) == 0 && (num & 0x55555555) != 0;
Check my code on github: link