Meaning of bitwise and(&) of a positive and negative number?

后端 未结 8 2033
名媛妹妹
名媛妹妹 2021-02-04 11:59

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

8条回答
  •  萌比男神i
    2021-02-04 12:27

    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.

提交回复
热议问题