public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (input.hasNextLine()) {
BigInteger number = new BigInteger(input.nextLine());
int bitLength = number.bitlength();
if (bitLength <= Bytes.SIZE)
System.out.println("\u8211 byte");
if (bitLength <= Short.SIZE)
System.out.println("\u8211 short");
if (bitLength <= Int.SIZE)
System.out.println("\u8211 int");
if (bitLength <= Long.SIZE)
System.out.println("\u8211 long");
if (bitLength > Long.SIZE)
System.out.println(number + " can't be fitted anywhere.");
}
}
Task : to find a suitable data type Sample Input :5
-150
150000
1500000000
213333333333333333333333333333333333
-100000000000000
Sample Output :
-150 can be fitted in:
short
int
long
150000 can be fitted in:
int
long
1500000000 can be fitted in:
int
long
213333333333333333333333333333333333 can't be fitted anywhere.
-100000000000000 can be fitted in:
long
Error 1:
error: cannot find symbol
int bitLength = number.bitlength();
^
Error 2:
symbol: method bitlength()
location: variable number of type BigInteger
Error 3:
error: cannot find symbol
if (bitLength <= Int.SIZE)
^
symbol: variable Int
location: class Solution
Sometimes, we need to check the data type of a variable to compute data because we can perform the logical operation with the same type of variables. In order to check the data type, we use getClass() and getSimpleName() method to get class and its name respectively.
Primitive data types - includes byte , short , int , long , float , double , boolean and char.
To check the type of any variable data type, we can use the type() function. It will return the type of the mentioned variable data type. Float data type is used to represent decimal point values.
Read the number line by line. Count bit using BigInteger
and divide it by 8 for switch
case simplification. Have a look at below code:
Scanner input = new Scanner(new File("so/input.txt"));
while (input.hasNextLine()) {
BigInteger number = new BigInteger(input.nextLine().trim());
int bitLength = number.bitLength();
int len = bitLength / 8;
StringBuilder output = new StringBuilder(number.toString() + " can be fitted in:\n");
switch (len) {
case 0:
output.append(" byte");
case 1:
output.append(" short");
case 2:
case 3:
output.append(" int");
case 4:
case 5:
case 6:
case 7:
output.append(" long");
System.out.println(output);
break;
default:
System.out.println(number.toString() + " can't be fitted anywhere.");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With