Power of 2
How to determine if an integer k is a power of 2. This is one of the questions you may face in an interview. The most obvious way is using a loop, which results in O(logn) complexity.
However, there are some beautiful tricks to do it in O(1).
Trick #1: using bitwise XOR operation ( from a website which I forgot the URL)
return k & (k ^ (k-1)) == k;
Trick #2: using bitwise AND operation ( thank VTL for this one :x )
return k & (k-1) == 0 ;

0 Comments:
Post a Comment
<< Home