Problem of the Day
A new programming or logic puzzle every Mon-Fri

Power of 2

Here's a simple one with some options for efficiency. Create a function that takes in a number and returns whether or not the number is a power of 2 or not.

Permalink: http://problemotd.com/problem/power-of-2/

Comments:

  • john smith - 10 years, 6 months ago

    java example

    I gess its simple.

    private static boolean isPower(int n) {
        if (n%2!=0)
            return false;
        if (n==2)
            return true;
        if (n%3==0 || n%5==0 || n%7==0 || n%9==0)
            return false;
    
        int p = 2;
        while(p<n){
            p*=2;
            if(n==p)
                return true;
        }
        return false;
    }
    

    reply permalink

  • Bryan St. Amour - 10 years, 6 months ago

    In C:

    int power(int n) { return ! (n & (n - 1) ); }

    reply permalink

  • Nick Krichevsky - 10 years, 6 months ago

    Python

    from math import log
    
    def log2(x):
        q=log(x,2)
        if round(q)==q:
            return True
        else:
            return False
    

    reply permalink

  • Anonymous - 10 years, 6 months ago

    #python 2.7
    x = int(raw_input("Enter a number> "))
    y = bin(x)
    if y.count("1") == 1:
        print True
    else:
        print False
    

    reply permalink

  • Ethan - 10 years, 6 months ago

    public static void checkPow(int n) {
            int pow = 1;
            for(int i = 0; i < n; i++) {
                pow *= 2;
                if(pow == n) {
                    System.out.println("true");
                    break;
                } else if(pow > n) {
                    System.out.println("false");
                    break;
                }
            }
        }
    

    reply permalink

  • Ethan - 10 years, 6 months ago

    I change my mind (thanks Nick):

    public static boolean checkPow(int n) {
        double pow = Math.log(n) / Math.log(2);
        System.out.println(pow);
        if(pow == Math.floor(pow)) {
            return true;
        } else {
            return false;
        }
    }
    

    https://gist.github.com/eglove/5f17f098a99f3bca41eb

    reply permalink

  • Matthew - 10 years, 6 months ago

    Python (2 or 3):

    def power(x): return True if bin(x).count("1")==1 else False
    

    reply permalink

  • Max Burstein - 10 years, 6 months ago

    Didn't know bin was a thing in python. Good stuff

    reply permalink

Content curated by @MaxBurstein