Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does (number & -number) mean in bit programming? [duplicate]

For example:

int get(int i) {     int res = 0;     while (i) {         res = (res + tree[i]) % MOD;         i -= ( (i) & (-i) );     }     return res; } 

A tree update function:

void update(int i, int val) {     while (i <= m) {         tree[i] = (tree[i] + val) % MOD;         i += ( (i) & (-i) );     } } 

Can you please explain what they do in the code by using ( (i) & (-i) )?

like image 740
SwadhIn Avatar asked Mar 08 '16 07:03

SwadhIn


People also ask

What does it mean in number?

Definition of in numbers : in total amount or quantity Fish were once plentiful in this river, but they have since declined in numbers.

Do numbers have meanings?

There are deeply spiritual meanings behind certain numbers that tie back to one's life path. Aside from spiritual meaning, many numbers also a deeper symbolic meaning, and it's essential to gain a deeper understanding of these meanings to understand how they affect the physical world within different cultures.

What is the meaning of number symbol?

The symbol # is known variously in English-speaking regions as the number sign, hash, or pound sign. The symbol has historically been used for a wide range of purposes including the designation of an ordinal number and as a ligatured abbreviation for pounds avoirdupois – having been derived from the now-rare ℔.

What does 777 mean?

Highly spiritual Angle Number 777 is the Sign of getting Divine Guidance. That indicates Its time to get rewards for your efforts. Angel numbers can mean different things. However, if you are seeing the angel number often and often then you should be happy.


1 Answers

Let me assume that negative value is represented using two's complement. In this case, -i can be calculated as (~i)+1 (flip bits, then add 1).

For example, let me consider i = 44. Then, in binary,

i           = 0000 0000 0000 0000 0000 0000 0010 1100 ~i          = 1111 1111 1111 1111 1111 1111 1101 0011 -i = (~i)+1 = 1111 1111 1111 1111 1111 1111 1101 0100 (i) & (-i)  = 0000 0000 0000 0000 0000 0000 0000 0100 

As you see, the least bit that is 1 can be calculated using (i) & (-i).

like image 116
MikeCAT Avatar answered Sep 30 '22 00:09

MikeCAT