Lets think of it in a different way. What sort of numbers are power of 2? If we look at the bit pattern we can say that the numbers which have a single 1 bit and the left and right bits from the 1 bit are all zeros. So what will be the number that represents the right bits? If you deduct 1 from given number N (i.e. N-1), then it should give number with all right bits set if the number is power of 2. What this means is that if we AND the given number N with N-1 and the result is 0 then the number is power of 2 otherwise not. If a number is not power of 2, it will have atleast single 1 on the right of it and the AND operation would result a number greater then 0. The check for power of 2 can be written in terms of code as:
bool is_power(unsigned int n) {
return n !=0 && (n & n-1) == 0;
}
No comments:
Post a Comment