How to check if a number is a power of 2 in C#?


A power of 2 is a number of the form 2n where n is an integer

The result of exponentiation with number two as the base and integer n as the exponent.

n2n
01
12
24
38
416
532

Example 1

 Live Demo

class Program {
   static void Main() {
      Console.WriteLine(IsPowerOfTwo(9223372036854775809));
      Console.WriteLine(IsPowerOfTwo(4));
      Console.ReadLine();
   }
   static bool IsPowerOfTwo(ulong x) {
      return x > 0 && (x & (x - 1)) == 0;
   }
}

Output

False
True

Example 2

 Live Demo

class Program {
   static void Main() {
      Console.WriteLine(IsPowerOfTwo(9223372036854775809));
      Console.WriteLine(IsPowerOfTwo(4));
      Console.ReadLine();
   }
   static bool IsPowerOfTwo(ulong n) {
      if (n == 0)
         return false;
      while (n != 1) {
         if (n % 2 != 0)
            return false;
         n = n / 2;
      }
      return true;
   }
}

Output

False
True


Updated on: 08-Aug-2020

455 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements