Skip to content

Instantly share code, notes, and snippets.

@robertmarsal
Created February 11, 2011 22:50
Show Gist options
  • Save robertmarsal/823214 to your computer and use it in GitHub Desktop.
Save robertmarsal/823214 to your computer and use it in GitHub Desktop.
recursive method to detect if a number is a power of 2
/**
* @author Robert Boloc
*/
public boolean isPower2(int v) {
if (v == 1) {
return true;
} else if (v % 2 != 0 || v == 0) {
return false;
} else {
return isPower2(v / 2);
}
}
@sadegh
Copy link

sadegh commented Oct 21, 2017

This also would work :)

public static boolean isPower2(int number) {
        return number > 0 &&
                (number & (number - 1)) == 0;
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment