Quantcast
Viewing all articles
Browse latest Browse all 38

Answer by Anil Gupta for How to check if a number is a power of 2

I see many answers are suggesting to return n && !(n & (n - 1)) but to my experience if the input values are negative it returns false values.I will share another simple approach here since we know a power of two number have only one set bit so simply we will count number of set bit this will take O(log N) time.

while (n > 0) {    int count = 0;    n = n & (n - 1);    count++;}return count == 1;

Check this article to count no. of set bits


Viewing all articles
Browse latest Browse all 38

Trending Articles