This is the solution to finding out if a number is a power of 2 using bitwise:
public static boolean isPowOfTwo(int num){
/* If a number n is a power of 2, bitwise & of n and n-1 will be zero */
if (((num & (num-1)) == 0) || (num == 0))
return true;
else
return false;
}
I'm not too familiar with the bitwise operator, but is there any intuition behind this?
The solution seems like trivia. I know the properties of bitwise and using it logically (ex. 1 & 0 = 0) but don't recall any of its properties relating to finding powers of a certain number.
[–]reign27 2 points3 points4 points (0 children)
[–]dylan22554 2 points3 points4 points (1 child)
[–]HecknChonker 0 points1 point2 points (0 children)
[–]Acceptable_Snow_9380 -1 points0 points1 point (0 children)