public class Solution {
public static int countSetBits(int n) {
// Write your code here.
int count = 0;
while(n>0) {
int bits = n&1;
if(bits == 1)
count++;
n=n>>1;
}
return count;
}
}
public class Solution {
public static int countSetBits(int n) {
// Write your code here.
int count = 0;
while(n>0) {
int bits = n&1;
if(bits == 1)
{
count++;
n=n>>1;
}
}
return count;
}
}
我试过两个代码 在第一个代码中,输出一直显示到值超过 7 时才显示任何内容 但是第二个工作得很好
在第一个中,
if
条件仅适用于count++
。在第二个中,大括号表示 if
条件适用于以下两个语句。这使得代码产生不同的结果。