差b/w 1 == n& 1和n& 1 == 1,n是一个无符号整数 [英] the difference b/w 1==n&1 and n&1==1 , n is an unsigned int

查看:118
本文介绍了差b/w 1 == n& 1和n& 1 == 1,n是一个无符号整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是来自leetcode的程序问题.它提供了一个未签名的int n,请您返回位"1"的数字;

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;
}

这很好用,但是

int hammingWeight(uint32_t n) {
int num=0;
for(;n!=0;n=n>>1)
{
    if(1==n&1)
    {
        num++;
    }
}
return num;
}

这有时不能工作!我猜想当用uint32_t计算1时出了点问题,但是我无法清楚地理解这一点.

this one cant work sometimes! i guess something is wrong when 1 calculate with an uint32_t,but i cant understand this clearly.

推荐答案

==的优先级高于&.因此,

== has higher precedence than &. Thus,

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

这篇关于差b/w 1 == n& 1和n& 1 == 1,n是一个无符号整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆