一、如何判断一个无符号整数是2的n次幂?
分析可以用枚举法判断一个数是2的n次幂,代码如下
package com.aim.getoff
import java.math.BigInteger;
import java.util.Scanner;
public class Judge2N
public static void main(String[] args) {
Scanner scc = new Scanner(System.in);
/*BigInteger n = scc.nextBigInteger();
System.out.println(isPow2(n));*/
int n = scc.nextInt();
System.out.println(isPow(n));
scc.close();
}
public static boolean isPow(int n) {
int m = 1;
/* for(int i=0;;i++) {
m = (int)Math.pow(2, i);
if(m==n) {
return true;
}else if(m>n) {
return false;
}
}*/
while(true) {
m = m<<1;
if(m==n) {
return true;
}else if(m>n) {
return false;
}
}
}
/**
* 计算超大整数
* @param n
* @return
*/
public static boolean isPow2(BigInteger n) {
BigInteger m = BigInteger.ONE;
/*for(int i=0;;i++) {
m = (int)Math.pow(2, i);
if(m==n) {
return true;
}else if(m>n) {
return false;
}
}*/
int i = 0;
while(true) {
m = m.shiftLeft(i);//左移位
if(m.compareTo(n)==0) {
return true;
}else if(m.compareTo(n)>0) {
return false;
}
i++;
}
}
}