For example, 8, 64, and 256 are the order numbers of 2 (8 is the 3rd power of 2, and 64 is the 6th power of 2 ), write a program in Java to determine whether an integer is the power of 2. Resolution: If a number is an order square of 2, the first of its binary number is generally 1, followed by several zeros. For example, 8 is 1000000, and 64 is. If you reduce this number by 1
For example, 8, 64, and 256 are the order numbers of 2 (8 is the 3rd power of 2, and 64 is the 6th power of 2 ), write a program in Java to determine whether an integer is the power of 2. Resolution: If a number is an order square of 2, the first of its binary number is generally 1, followed by several zeros. For example, 8 is 1000000, and 64 is. If you reduce this number by 1
For example, 8, 64, and 256 are the order numbers of 2 (8 is the 3rd power of 2, and 64 is the 6th power of 2 ), write a program in Java to determine whether an integer is the power of 2.
Resolution: If a number is an order square of 2, the first of its binary number is generally 1, followed by several zeros. For example, 8 is 1000000, and 64 is.
If you subtract 1 from this number and perform a phase and (&) operation with this number, it should be all 0 (8 and 7, a binary number is 1000, and a binary value is 111, (1000-1) & 111 = 0 ).
That is, (D-1) & d = 0.
The Code is as follows:
Package cn. wuhan. unit6; import java. io. *; class InputData {static private String s = ""; static public void input () {// enter a line of characters from the keyboard, save to string s BufferedReader bu = new BufferedReader (new InputStreamReader (System. in); try {s = bu. readLine () ;}catch (IOException e) {}} static public int getInt () {// static method getInt (), you can call input () directly with the class name (); return Integer. parseInt (s); // convert the string to an integer and return the Result} class Result {// calculate the sum of squares cube void print (int d) {// S Ystem. out. println (d + "square:" + d * d); // System. out. println (d + "Cube:" + d * d); if (D-1) & d) = 0 & (d! = 0) System. out. println ("order 2"); else System. out. println ("not 2 order") ;}} public class PrintResult {public static void main (String [] args) {Result result = new Result (); System. out. println ("enter an integer:"); int a = InputData. getInt (); result. print ();}}
The effect is as follows: