Search code examples
c++coperator-precedence

the difference b/w 1==n&1 and n&1==1 , n is an unsigned int


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.


Solution

  • == has higher precedence than &. Thus,

    • n&1==1 is n & (1==1), while
    • 1==n&1 is (1==n) & 1.