231. Power of Two

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

public class Solution {
    public boolean isPowerOfTwo(int n) {
        if (n == 0) return false;
        if (n == 1) return true;
        if (n % 2 == 1) return false;
        return isPowerOfTwo(n / 2);
    }
}
// Can also use bit manipulation: n && n - 1;
public class Solution {
public boolean isPowerOfTwo(int n) {
if (n > 0 && (n & (n - 1)) == 0) return true;
return false;
}
}
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