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

痴心易碎 提交于 2019-12-11 03:12:28

问题


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 is n & (1==1), while
  • 1==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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!