A function to calculate sum where I encountered with this statement ..plz help
int get_sum(int x) {
int p = 0, k;
for (k = x; k > 0; k -= k & -k)
p += bit[k];
return p;
}
A function to calculate sum where I encountered with this statement ..plz help
int get_sum(int x) {
int p = 0, k;
for (k = x; k > 0; k -= k & -k)
p += bit[k];
return p;
}
This expression:
k -= (k & (-k))
Is a tricky way of taking the least significant bit that is set in a positive number and clearing that bit. It is dependent on two's compliment representation of negative numbers.
The first part, k & (-k)
isolates the least significant bit that is set. For example:
1 & -1
:
00000001
& 11111111
--------
00000001
2 & -2
:
00000010
& 11111110
--------
00000010
24 & -24
:
00011000
& 11101000
--------
00001000
When this value is subtracted from the orignal k
, it clears that bit as a result.
So as the loop progresses, the value of k
is reduced 1 bit at a time, starting with the lowest. So if for example x
was 52, k
would be 52, then 48 (52 - 4), then 32 (48 - 16), and would exit at 0 (32 - 32).
As to why the program is doing this, that depends entirely on the definition of bit
and what it stores.