Twenty C# Questions Explained: (07) How do you check if a number is a power of 2?

Sign in to queue

The Discussion

  • User profile image

    Nice trick. Good to learn something new and different.

  • User profile image

    // Works for any power
    private Boolean IsXPow(int n, int x)
    int Dummy;
    return int.TryParse((Math.Log(n) / Math.Log(x)).ToString(), out Dummy);

  • User profile image

    Thank you for the post. This is new. However, I have a question. What makes you take the number, minus 1, and use and operate with it? I mean, what's the rational behind of doing it?

Add Your 2 Cents