google-code-prettify

Friday 4 January 2013

Determine if a number is power of 2

How can you check if a number is power of 2? This is not so hard to solve and in fact there are many ways you can implement a solution. One of the most obvious solutions is probably the one where you repeatedly divide the number by 2 until you end with 1 (in case the number is power of 2) or you reach an odd number higher than 1 (in case the number is not power of 2).
boolean isPowerOf2(int x) {
    while (((x % 2) == 0) && x > 1) {
        x /= 2;
    }
    return (x == 1);
}

A lot nicer solution is the one using bit operation:
boolean isPowerOf2(int x) {
    return x > 0 && (x & (x - 1)) == 0;
}

Here the idea is that every number that is a power of 2 has exactly one bit set to 1 in its binary representation and if you subtract 1 from this number you get a number where all first bits (starting from right) are 1 in the binary representation:
2    =  00000010     2  - 1 = 1  = 00000001
4    =  00000100     4  - 1 = 3  = 00000011
8    =  00001000     8  - 1 = 7  = 00000111
16   =  00010000     16 - 1 = 15 = 00001111
...
And if you do a bitwise AND (operator '&') on the original number and the original number subtracted by 1, we get 0:
2  & 1  = 00000010 & 00000001 = 0
4  & 3  = 00000100 & 00000011 = 0
8  & 7  = 00001000 & 00000111 = 0
16 & 15 = 00010000 & 00001111 = 0
...

No comments:

Post a Comment