如何找出在Java中存储给定整数的正确数据类型



假设给了我一个数字,并要求我找出哪种数据类型适合存储它。例如,假设数字是741,那么它可以存储在shortintlong数据类型中。但是,如果输入的数字很大,例如-10000000000,则只能以数据类型存储。根据用户输入的数字,我需要提供所有可能的数据类型,可以用来存储它

附言:这是一个在Hackerrank平台上用Java数据类型给出的问题。问题链接:-https://www.hackerrank.com/challenges/java-datatypes/problem?h_r=next-挑战&h_v=zen&isFullScreen=错误

您可以使用原始数据类型包装器,它们都包含一个常量值,其中包含它们可以容纳的最大值和最小值。

它们是:

Byte.MIN_VALUE; //-128
Byte.MAX_VALUE; //127
Short.MIN_VALUE; //-32768
Short.MAX_VALUE; //32767
Integer.MIN_VALUE; //0x80000000
Integer.MAX_VALUE; //0x7fffffff
Long.MIN_VALUE; //0x8000000000000000L
Long.MAX_VALUE; //0x7fffffffffffffffL

这是我的解决方案:

long n = 0;
try {
n = new Scanner(System.in).nextLong();
} catch (InputMismatchException e) { //we're expecting just numbers anyway
System.out.println("doesn't fit anywhere");
}

if (n > 0) {
//since n is positive,
//first let's evaluate if it's not too big to fit in a byte data type
if (n <= Byte.MAX_VALUE) System.out.println("fits in a byte");

//now let's evaluate if n is not too big to fit in a short data type
if (n <= Short.MAX_VALUE) System.out.println("fits in a short");

//now let's evaluate if n is not too big to fit in an int data type
if (n <= Integer.MAX_VALUE) System.out.println("fits in an int");


} else {
//similar code for negative numbers
if (n >= Byte.MIN_VALUE) System.out.println("fits in a byte");
if (n >= Short.MIN_VALUE) System.out.println("fits in a short");
if (n >= Integer.MIN_VALUE) System.out.println("fits in an int");
}
//well, since we already verified n doesn´t overtake a long with try block
// n will always fit in a long
System.out.println("fits in a long");

最新更新