Meaning of bitwise and(&) of a positive and negati

2020-05-23 19:40发布

Can anyone help what n&-n means?? And what is the significance of it.

8条回答
forever°为你锁心
2楼-- · 2020-05-23 20:37

On pretty much every system that most people actually care about, it will give you the highest power of 2 that n is evenly divisible by.

查看更多
ゆ 、 Hurt°
3楼-- · 2020-05-23 20:40

Because x & -x = {0, 1, 2, 1, 4, 1, 2, 1, 8, 1, 2, 1, 4, 1, 2, 1, 16, 1, 2, 1, 4, 1, 2, 1, 8, 1, 2, 1, 4, 1, 2, 1, 32} for x from 0 to 32. It is used to jumpy in the for sequences for some applications. The applications can be to store accumulated records.

for(;x < N;x += x&-x) {
    // do something here
    ++tr[x];
}

The loop traverses very fast because it looks for the next power of two to jump.

查看更多
登录 后发表回答