Sunday, 1 May 2016

How to check if a number is power of 2 ?


Solution #1. Divide num by 2 recursively
Time complexity : O(log2n)


Solution #2. Using Bitwise & operator with num and num-1
boolean isPowerOf2 = (num & (num-1))==0;

Time complexity : O(1)

Example
num = 8
n    = 8 = 1000
n-1 = 7 = 0111
-------------------
               0000 => Power of 2, Yes.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.