Skip to content

Instantly share code, notes, and snippets.

@booknara
Last active April 21, 2016 22:21
Show Gist options
  • Save booknara/ccec649136963b4e96e2d02383b4cdae to your computer and use it in GitHub Desktop.
Save booknara/ccec649136963b4e96e2d02383b4cdae to your computer and use it in GitHub Desktop.
Checking the number is Power of 2
/**
* Created by Daehee Han(@daniel_booknara) on 4/21/16.
*/
public class Power2 {
public static void main(String[] args) {
for (int i = 1; i < 10; i++) {
if (isPower2(i))
System.out.println(i + " is power of 2");
else
System.out.println(i + " is NOT power of 2");
if (isEnhancedPower2(i))
System.out.println(i + " is power of 2");
else
System.out.println(i + " is NOT power of 2");
if (isEnhanced2Power2(i))
System.out.println(i + " is power of 2");
else
System.out.println(i + " is NOT power of 2");
}
}
public static boolean isPower2(int value) {
while (value != 1) {
if (value % 2 != 0)
return false;
value = value / 2;
}
return true;
}
public static boolean isEnhancedPower2(int value) {
return ((value & -value) == value);
}
public static boolean isEnhanced2Power2(int value) {
return ((value & value - 1) == 0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment