Tuesday, October 27, 2020

Given an integer, write a method to determine if it is a power of two.

Approach: According to Brian Kernighan algorithm, which we have used in calculating Hamming Weight, subtracting '1' from a number flips all the bits after the rightmost set bit including the rightmost set bit so if a number n is a power of 2 then n & n - 1 will be 0.


Implementation in C#:

        public bool IsPowerOfTwo(int n)

        {

            return n != 0 && n != int.MinValue && (n & n - 1) == 0;

        }


Complexity: O(1)

No comments:

Post a Comment