1 package algorithm; 2 3 /** 4 * Created by moi on 2017/10/18. 5 */ 6 public class PowerOf2 { 7 8 public static int powOf2(int n){ 9 if(n==0){10 return 1;11 }12 if(n>31){13 throw new RuntimeException("n>31 is too big.");14 }15 int base = 2;16 while(n>1){17 base = base << 1;18 System.out.println(base);19 n--;20 }21 return base;22 }23 24 public static boolean checkPowerOf2(int n) {25 // write your code here26 boolean flag = true ;27 28 if ( n < 1 ){29 return false;30 }31 32 while( n>= 2 ){33 // 1的二进制是 最低位为1,其余各位为0,所以这里 n & 1 即n的最低位和 1的最低位1 进行与,如果是偶数,结果就是0,奇数就是1.34 if ( (n & 1) == 1 ){35 flag = false ;36 break;37 }38 n = n >> 1 ;39 }40 return flag ;41 }42 43 public static void main(String[] args) {44 PowerOf2.powOf2(3);45 }46 }