How to get Integer.MAX_VALUE in Java without using Integer class

I have a question that has completely surpassed me. I have to create a variable that is Integer.MAX_VALUE ... (in Java)

// The answer must contain balanced parentesis
public class Exercise{

  public static void main(String [] arg){
    [???]
    assert (Integer.MAX_VALUE==i);
  }
}

The problem is that the source code cannot contain the words "Integer", "Float", "Double" or any numbers (0-9).

+4
source share
6 answers

Here is a short method:

int ONE = "x".length();
int i = -ONE >>> ONE; //unsigned shift

This works because the maximum integer value in binary is all units except the top (signed) bit, which is zero. But -1 in twos binary complement is all, therefore, shifting the -1 bit by one bit to the right, you get the maximum value.

11111111111111111111111111111111 // -1 in twos compliment
01111111111111111111111111111111 // max int (2147483647)
+5

.

int i = Integer.MAX_VALUE;

- , .

Integer.MAX_VALUE, " " "-" Integer, . .

+2

:

int ONE = "X".length();
int max = ONE;
while (max < max + ONE) {
   max = max + ONE;
}

.

(, , , "" -. , ONE, ...)

+1

, : "Integer", "Float", "Double" (0 - 9)

Java , Integer, a char:

char aCharacter = 'a';
int asInt = (int) aCharacter;
System.out.println(asInt); //Output: 97

:

char aCharacter = 'a';
char anotherCharacter = 'b';
int sumOfCharacters = aCharacter + anotherCharacter;
System.out.println(sumOfCharacters); //Output: 195

, 2147483647 .

0

, Integer . MIN_VALUE MAX_VALUE, .

, . MAX_VALUE + 1 = MIN_VALUE.

, , . MIN_VALUE-1 = MAX_VALUE.

, int, , , , Integer.MAX_VALUE

public static void main(String [] arg) {

    int i = -1

    while (i<0) {
        i--;
    }
    System.out.println(i);
}
0

, :

int two = "xx".length();
int thirtyone = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx".length();
System.out.println(Math.pow(two, thirtyone)-1);

How did I go ?: P

I like this beatwig though ...

0
source

Source: https://habr.com/ru/post/1535200/


All Articles