Frage

Somebody please explain how to to solve such task ?

int x = (Integer.MIN_VALUE << 1) >> 1;

I would like to understand how to solve the examples like that ? What I need to do if the sample contains Integer.MIN_VALUE (Integer.MAX_VALUE) ?

War es hilfreich?

Lösung

The shift operator (y << x) just shifts the bits of y to the left by 'x' places. The right-most bit becomes 0. The >> operator shifts to the right, and the value of the left-most bit (the sign bit) is copied into the new left-most bit.

To work out your answer you need the bit pattern for the initial value (Integer.MIN_VALUE) and then do the operations to get the resulting bit pattern. You can then convert that back to a decimal value.

Andere Tipps

Well, you could just follow short tutorial http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html

In a nutshell, by doing << (left shift) you move binary representation of your number to the left
i.e. if x = 0b0010, then x << 1 becomes 0b0100, new 'zero' bit is appended to the right.

Similarily, for right shift : if x = 0b1010, then x >> 1 becomes 0b1101, rightmost bit dissapears, new 'one' bit (depends on value of leftmost bit) is appended on the left.

You need to find out binary representation of Integer.MIN_VALUE to resolve your puzzle, which should not be very tricky.

If you're trying to understand how the bit shift operators work, I would suggest two things:

  • First, read some guides on what they do: here and here for example.
  • Write some code and look at the output. That way you can see how bit shift operators actually affect values like Integer.MIN_VALUE and Integer.MAX_VALUE.

The min-value is represented as 10000000000000000000000000000000. It's 32 1's. For clarity, let's pretend we're working with only 4 bits. In this case, the MIN_INT would be 1000. This will apply to 32 bits as well.

We then want to left shift << by 1, which would shift all the bits over to the left by 1 position. Thus, 1000 would become 0000. This is like multiplying by two (although in this case we get overflow!),

Then we want to right shift '>>' by 1, which would shift all the bits to the right by 1 position. In this case, it would become 0000 as the sign bit is replicated when you right shift. If it was 1111 it would become 1111. This is like dividing by two, except in some cases, as you must be weary of the sign bit copying over.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top