Java Datatypes Hackerrank Solution

Introduction

In Java Datatypes Hackerrank Solution, we are given an integer input, we have to determine the primitive datatypes of java that can store this integer. Java has 4 primitive datatypes for storing integers. They are

  • Byte: It can hold 8 bit signed integer
  • Short: It can hold 16-bit signed integer
  • Int: It can hold a 32-bit signed integer
  • Long: It can hold a 64-bit signed integer

Given an input, we have to print which of these datatypes are capable of storing it.

Byte has 8 bits of space out of which 1 bit is reserved for the sign. Hence only 7 bits are available. Thus a bit can store values between -2^7 and 2^7 – 1. Which is equivalent to -128 to 127.

Similarly, short can store values between -2^15 and 2^15-1 i.e. 32768 to 32787.

Int can store values between -2^32 and 2^32-1 i.e -2147483647 to 2147483648.

And long can store values between -2^64 and to 2^64-1.

We can use these conditions in our code to find out suitable data types.

Java Datatypes Hackerrank Solution

import java.util.*;
import java.io.*;


class Solution{
    public static void main(String []argh)
    {
        Scanner sc = new Scanner(System.in);
        
        int t=sc.nextInt();

        for(int i=0;i<t;i++)
        {
            try
            {
                long x=sc.nextLong();
                if(x > Long.MAX_VALUE || x < Long.MIN_VALUE){
                    System.out.println(x+" can't be fitted anywhere.");
                }
                else{
                    System.out.println(x+" can be fitted in:");
                
                    if(x>=-128 && x<=127){
                        System.out.println("* byte");
                    }
                    if (x>= -32768 && x <= 32767){
                        System.out.println("* short");
                    }
                    if(x>=-2147483648 && x<=2147483647){
                        System.out.println("* int");
                    }
                    if(x>=Long.MIN_VALUE && x<=Long.MAX_VALUE){
                        System.out.println("* long");
                    }
                }
            
            }
            catch(Exception e)
            {
                System.out.println(sc.next()+" can't be fitted anywhere.");
            }

        }
    }
}

Input:

  • 5
  • -150
  • 150000
  • 1500000000
  • 213333333333333333333333333333333333
  • -100000000000000

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

HackerRank ScreenShot:

HackerRank ScreenShot for Java Datatypes Hackerrank Solution

We hope we solved your problem of Java Datatypes Hackerrank Solution.


Also Read:

Share:

Author: Ayush Purawr