在查找变量循环值的第一个循环中出现了问题。当我注释掉那个特定的循环并运行其余的代码时,代码运行得很完美,但当我用for循环运行代码时,我会得到不同的答案。请帮忙。
代码:
public static void main(String [] args){
Scanner sc = new Scanner (System.in);
System.out.print("number : ");
int n = sc.nextInt();
int inc = 0;
int loops = 0;
**// problem
for(int i = 0; n>0; i++){
int b = n>>=i;
loops = i;
}**
for (int i = 0; i<=loops; i++){
int bit = 1<<i;
if((bit & n) == 0){
}else{
inc = inc + 1;
}
}
if (inc==1){
System.out.println("power");
}else{
System.out.println("not power");
}
}
这里有一种方法,但肯定不是最有效的。
int[] vals = {0, 1, 2, 4, 11, 13, 18, 28, 16, 46, 32 };
for (int v : vals) {
System.out.printf("%2d - %s%n", v, isPowerOf2(v) ? "yes" : "no");
}
打印
0 - no
1 - yes
2 - yes
4 - yes
11 - no
13 - no
18 - no
28 - no
16 - yes
46 - no
32 - yes
以下只是对位进行计数。如果计数等于1,则该值为2的幂。
- 如果v<=0返回false
- 初始化计数
- 如果设置了低位,则将计数增加1
- 如果大于1,立即返回false
- 否则执行无符号右移1并继续
- 当v==0时终止测试
- 返回true,因为计数必须为1
public static boolean isPowerOf2(int v) {
if (v <= 0) {
return false;
}
int count = 0;
do {
if ((count += (v & 1)) > 1) {
return false;
}
} while ((v>>>=1) != 0);
return true;
}
在不使用比特操作的情况下,可以简单地使用Integer.bitCount()
方法来对比特进行计数。