本文介绍了差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==1是n & (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是一个无符号整数
发布评论