How to check if a number is a power of 2

后端 未结 25 1532
爱一瞬间的悲伤
爱一瞬间的悲伤 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 03:56

    in this approach , you can check if there is only 1 set bit in the integer and the integer is > 0 (c++).

    bool is_pow_of_2(int n){
        int count = 0;
        for(int i = 0; i < 32; i++){
            count += (n>>i & 1);
        }
        return count == 1 && n > 0;
    }
    
    

提交回复
热议问题