Quick actions

cmd+k|ctrl+k

Navigation

Languages

Is power of two in C#

Snippet info

Language

Csharp

Visibility

public

Author

patrykstachowiak

Created

2025-03-10T20:24:11.370099Z

Updated

2025-03-10T20:39:51.59592Z

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;
    }
}
INFO