What does x += x & -x mean?

谁都会走 提交于 2021-02-07 03:28:38

问题


I found that many people use x += x & -x, x -= x & -x to solve the interval tree problem. Can you explain what that equation means?

void update(int m, int x) { 
    m++;
    while (m < N) {
        t[m] = t[m] + x;
        m += m & -m;
    }
}
int query(int m) { 
    int result= 0;
    m++;
    while (m > 0) {
        result = result + t[m];
        m -= m & -m;
    }
    return result;
}

回答1:


Note: This answer (like the method itself) assumes signed integers are represented in two's complement form.

The expression x & -x is a quick - but admittedly arcane - way of getting the value represented by the lowest set bit in x (when all other bits are clear). This is sometimes known as the weight of the bit, and is numerically equal to 2 raised to the power of the bit's position (where the least significant bit is position 0).

The method relies on the fact that there can only be a single bit that is set in the binary (2s-comp) representations of both x and -x - and this will actually be the least significant set bit in x.

There are some good explanations of how this works, with many examples, here on Quora.

In the update and query functions you show, the amount by which to increase/decrease m in the while loops is thus weighted according to the position of the least significant set bit in the (original) m.

Feel free to ask for further clarification and/or explanation (but I don't wish to copy/paste or paraphrase too much of the discussion I've linked).




回答2:


As @Adrian has already given an excellent answer about what the expression means I'll just complement it with a simple example on how it works.

Let's consider that our x is a 4-bit number(for simplicity) 1100b. Then,

  1. x is 0000 1100b (its lowest set bit is at position 2 (index starts from left at 0)
  2. -x is 1111 0100b as 0000 1100b + 1111 0100b = 0b
  3. -x & x results in 0100b. The only set bit is at the same position as the rightmost bit in x - at position 2.



回答3:


In Binary Indexed Tree (Fenwick_tree) these operations are updating and querying the Tree. To query the Tree you are finding the parent of an element by resetting it's rightmost set bit. To update the Tree you keep adding least significant bit to the current index to find all the elements to update.




回答4:


Another way of interpreting it can be as follows:

Let X be a number. Then X&-X represents the greatest power of 2 that divides X.

Examples:

  1. Let X = 10, then X&-X will give 2.
  2. Let X = 7, then X&-X will give 1.
  3. Let X = 4, then X&-X will give 4.


来源:https://stackoverflow.com/questions/58995116/what-does-x-x-x-mean

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