1. 程式人生 > >java:給定一個整型數,判斷是否是2的冪次

java:給定一個整型數,判斷是否是2的冪次

第一種方法:

import java.util.Scanner;

public class MiCi {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
while(in.hasNext()){
int n = in.nextInt();
if(n >0){
int m = n^(n-1);
if(m == 2*n-1){
System.out.println("Yes");
}
}else{
System.out.println("No");
}
}

}

第二種方法:

import java.util.Scanner;
public class MiCi {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
while(in.hasNext()){
int n = in.nextInt();
if(n <= 0){
System.out.println("No");
}else{
int m = n&(n-1);
if(m == 0){
System.out.println("Yes");
}else{
System.out.println("No");
}
}

}
}
}