How to check if a number is a power of 2

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

    Improving the answer of @user134548, without bits arithmetic:

    public static bool IsPowerOfTwo(ulong n)
    {
        if (n % 2 != 0) return false;  // is odd (can't be power of 2)
    
        double exp = Math.Log(n, 2);
        if (exp != Math.Floor(exp)) return false;  // if exp is not integer, n can't be power
        return Math.Pow(2, exp) == n;
    }
    

    This works fine for:

    IsPowerOfTwo(9223372036854775809)
    
    0 讨论(0)
提交回复
热议问题