How to check if a number is a power of 2

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

    After posting the question I thought of the following solution:

    We need to check if exactly one of the binary digits is one. So we simply shift the number right one digit at a time, and return true if it equals 1. If at any point we come by an odd number ((number & 1) == 1), we know the result is false. This proved (using a benchmark) slightly faster than the original method for (large) true values and much faster for false or small values.

    private static bool IsPowerOfTwo(ulong number)
    {
        while (number != 0)
        {
            if (number == 1)
                return true;
    
            if ((number & 1) == 1)
                // number is an odd number and not 1 - so it's not a power of two.
                return false;
    
            number = number >> 1;
        }
        return false;
    }
    

    Of course, Greg's solution is much better.

提交回复
热议问题