Skip to content

Instantly share code, notes, and snippets.

@Experiment5X
Created March 25, 2014 12:54
Show Gist options
  • Save Experiment5X/9761259 to your computer and use it in GitHub Desktop.
Save Experiment5X/9761259 to your computer and use it in GitHub Desktop.
I saw an interview question on reddit to check if a given number is a power of 2 in one line. Here's a solution in Java.
public static boolean isPowerOf2(int num)
{
return Math.log(num) / Math.log(2) == (double)(31 - Integer.numberOfLeadingZeros(num));
}
@hetelek
Copy link

hetelek commented Mar 31, 2014

public static boolean isPowerOf2(int i)
{
    return i & i - 1 == 0;
}

pussy.

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