Power of Two

Given an integer, write a function to determine if it is a power of two.

    public boolean isPowerOfTwo(int n) {
        if (n < 0) 
            return false; 
        int one = 1;
        int count = 0; 
        for (int i = 0; i < 32; i++) {
            if ( (n & 1) == 1) {
                count++; 
                
            }
            n = n >> 1; 
        }
        return (count == 1);
    }

Comments: the number that is the power of 2 has only the first digit as 1 in its binary form.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s