0

I've been asked by my tutor to find a way of getting an Integer of Max value in java without using the actual word Integer, along with Float, Double and the numbers 0-9. He also encouraged us to use the web to find answers.

I would rather not post the code but all it really is is a comment stating the above, some class and method code and an assert line checking that i==Integer.MAX_VALUE.

Ive spent a few days working on this and ive come to the conclusion that I need to somehow use a Long to make a value that will wrap around to Integer.MAX_VALUE when converted to an int, I just can't figure out the actual code to do this. Any help would be nice.

user987339
  • 10,519
  • 8
  • 40
  • 45
Alex
  • 11
  • 2
  • 4

3 Answers3

0

You do not need a long...

You can use, for instance, ~0 >>> 1; ~0 is 0xffffffff, right shifting by 1 without carrying the sign bit will be 0x7fffffff, which is Integer.MAX_VALUE.

Note the use of >>> instead of >>; >> will "carry" the sign bit when shifting, and this is not what you want.

fge
  • 119,121
  • 33
  • 254
  • 329
0

int i = 0b01111111111111111111111111111111;

Its the binary representation of maximal Integer value in java. There are 32 bits and the first one is set to zero, because java uses Two's complement to realize negative values.

Kousalik
  • 3,111
  • 3
  • 24
  • 46
0

What you must know to get the maximum int value is:

  • an integer is composed of 4 bytes
  • the sign of an integer is represented by the highest bit (which is bit 31, counting from 0)
  • negative integers do have bit 31 set to 1
  • positive integers do have bit 31 set to 0
  • positive and negative integers are represented using Two's complement

With this knowledge in place, you may use bit operations to calculate the max integer value. The larges integer value has all bit set to 1, except bit 31. Hence, applying the ~ operator (bitwise not) to 0 result in all 32 bits set to 1. Shifting all bits one position to the right using the >>> operator (which sets bit 31 to 0) results in the largest possible integer.

int max = (~0) >>> 1;
Harmlezz
  • 7,972
  • 27
  • 35