using System;
using System.Collections.Generic;
using System.Linq;
class MainClass {
static void Main() {
int number = 4;
if (IsPowerOfTwo(number))
Console.WriteLine($"{number} is a power of 2.");
else
Console.WriteLine($"{number} is NOT a power of 2.");
if (IsPowerOfTwoBitwise(number))
Console.WriteLine($"{number} is a power of 2. (Bitwise)");
else
Console.WriteLine($"{number} is NOT a power of 2. (Bitwise)");
}
O(log(n))
static bool IsPowerOfTwo(int n)
{
if (n <= 0)
return false;
while (n > 1)
{
if (n % 2 != 0)
return false;
n /= 2;
}
return true;
}
O(1)
static bool IsPowerOfTwoBitwise(int n)
{
return n > 0 && (n & (n - 1)) == 0;
}
}