Last active
April 21, 2016 22:21
-
-
Save booknara/ccec649136963b4e96e2d02383b4cdae to your computer and use it in GitHub Desktop.
Checking the number is Power of 2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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