How to check if a number is a power of 2

后端 未结 25 1578
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 03:30

Today I needed a simple algorithm for checking if a number is a power of 2.

The algorithm needs to be:

  1. Simple
  2. Correct for any ulong
25条回答
  •  旧巷少年郎
    2020-11-22 04:19

    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

提交回复
热议问题