问题
this is a program problem from leetcode.it gives an unsigned int n,ask you to return the numbers of bit '1';
int hammingWeight(uint32_t n) {
int num=0;
for(;n!=0;n=n>>1)
{
if(n&1==1)
{
num++;
}
}
return num;
}
this works perfectly,but
int hammingWeight(uint32_t n) {
int num=0;
for(;n!=0;n=n>>1)
{
if(1==n&1)
{
num++;
}
}
return num;
}
this one cant work sometimes! i guess something is wrong when 1 calculate with an uint32_t,but i cant understand this clearly.
回答1:
==
has higher precedence than &
. Thus,
n&1==1
isn & (1==1)
, while1==n&1
is(1==n) & 1
.
来源:https://stackoverflow.com/questions/31490996/the-difference-b-w-1-n1-and-n1-1-n-is-an-unsigned-int