如何在不使用Integer类的情况下获取Java中Integer.MAX_VALUE的值 [英] How to get the value of Integer.MAX_VALUE in Java without using the Integer class

查看:141
本文介绍了如何在不使用Integer类的情况下获取Java中Integer.MAX_VALUE的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个完全困扰我的问题. 我必须创建一个等于Integer.MAX_VALUE ...(在Java中)的变量

I have this question that has completely stumped me. I have to create a variable that equals 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);
  }
}

挑战在于源代码中不能包含单词"Integer","Float","Double"或任何数字(0-9).

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

推荐答案

这是一个简洁的方法:

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

之所以可行,是因为二进制的最大整数值全为1,除了最高(符号)位为零.但是二进制补码二进制数-1都是1,因此将-1右移一位,就可以得到最大值.

This works because the max integer value in binary is all ones, except the top (sign) bit, which is zero. But -1 in twos compliment binary is all ones, so by bit shifting -1 one bit to the right, you get the max value.

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

这篇关于如何在不使用Integer类的情况下获取Java中Integer.MAX_VALUE的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆