How to check if a number is a power of 2

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

    Mark gravell suggested this if you have .NET Core 3, System.Runtime.Intrinsics.X86.Popcnt.PopCount

    public bool IsPowerOfTwo(uint i)
    {
        return Popcnt.PopCount(i) == 1
    }
    

    Single instruction, faster than (x != 0) && ((x & (x - 1)) == 0) but less portable.

提交回复
热议问题