ProveMeRight's blog

By ProveMeRight, history, 17 months ago, In English

209248600

...
int a = x;
int b = 0;

for(int i= 29;i>=0;i--)
    {
        if((x & (1 << i)) > 0)
        {
            continue;
        }

        if((2*x - a - b) >= (2 << i))
        {
            // bug(a,b);
            a += (1 << i);
            b += (1 << i);
        }
    }

When I am making the start from i= 30 or more, it makes a negative. Why?

Note: I defined int as long long. Still, It's doing the same.

Can anyone please explain?

  • Vote: I like it
  • +1
  • Vote: I do not like it

»
17 months ago, # |
  Vote: I like it +5 Vote: I do not like it

When you are left shifting, do :
(1ll << i), (2ll << i)

  • »
    »
    17 months ago, # ^ |
      Vote: I like it +5 Vote: I do not like it

    But why? I mean Integer can hold upto 2^31. Then why it's changing the sign bit.

    • »
      »
      »
      17 months ago, # ^ |
        Vote: I like it +5 Vote: I do not like it

      Actually, int can hold upto $$$2^{31} - 1$$$, starting from $$$2^{31}$$$ it overflows