Using bitwise & operator and + in Java giving inconsistent results

↘锁芯ラ 提交于 2019-12-01 17:40:48

In Java, + has higher precedence than &. Your expression num+n&1 will add num and n and then take the lowest bit.

To fix this, try making the statement in the second example num=num+(n&1);.

Operator precedence. + has higher priority than &. Your code

num=num+n&1

Will be executed like

num=(num+n)&1

Look here

Operators precedence

int x=n&1;
num=num+x;

and

num=num+n&1;

are different.
You're doing the bitwise & in a different moment.

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