判断一个整数不是2的阶次方树
如果是一个2的阶次方,那么它的二进制数的首位一般是1,后面接若干个0。比如8就是1000,64是100 0000。 如果将这个数减1后,再与该数做和&运算,则改全为0.
package cn.usst.DataTest; import java.io.*; /** * 从键盘输入一个值 */ public class InputData { static private String s = ""; static public void input() { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try { s = br.readLine(); } catch (IOException e) { throw new IllegalArgumentException(); } } static public int getInt(){ input(); return Integer.parseInt(s); } }
package cn.usst.DataTest; /** * 判断一个整数不是2的阶次方树 * @author G-Xia * */ public class Result { void print(int d){ if (((d-1)&d) == 0 && (d !=0 )){ System.out.println("是2的阶次方"); }else{ System.out.println("不是2的阶次方"); } } }
package cn.usst.DataTest; public class DateTest { public static void main(String[] args) { Result result = new Result(); System.out.println("please input integer:"); int a = InputData.getInt(); result.print(a); } }
原文地址:http://blog.csdn.net/ankeyuan/article/details/39649037