java面试每日一题9
题目:判断一个数是否是2的方次幂
public class Power { public static void main(String [] args) throws NumberFormatException, IOException{ System.out.println("请输入一个数:"); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int i=Integer.parseInt(br.readLine()); isPower(i); } private static void isPower(int num){ if(((num - 1) & num) == 0){ System.out.println("是方次幂"); }else{ System.out.println("不是方次幂"); } } }
private static void isPower(int num){ boolean flag=false; for(int i=num;i>0;i--){ int a = num/2; int b=num%2; num=a; System.out.println("num是"+num+"取余是"+b); if(num>2){ System.out.println(88); } if(num<=2){ int c=(num*2+b)%2; if(c==0){ flag=true; }else{ flag=false; } break; } } if(flag==true){ System.out.println("该数是2的方次幂"); } if(flag==false){ System.out.println("该数不是2的方次幂"); } }