In this hacker rank Java Datatypes problem solution in the java programming language you have Given an input integer, you must determine which primitive data types are capable of properly storing that input.

HackerRank Java Datatypes problem solution


HackerRank Java Datatypes problem 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();
            System.out.println(x+" can be fitted in:");
            if(x>=-128 && x<=127)System.out.println("* byte");
            //Complete the code
            if(x >= -Math.pow(2, 15) && x <= Math.pow(2, 15) - 1)
                System.out.println("* short");
            if(x >= -Math.pow(2, 31) && x <= Math.pow(2, 31) - 1)
                System.out.println("* int");
            if(x >= -Math.pow(2, 63) && x <= Math.pow(2, 63) - 1)
                System.out.println("* long");
        }
        catch(Exception e)
        {
            System.out.println(sc.next()+" can't be fitted anywhere.");
        }

    }
}
}


Second solution in java8 programming.

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

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int t = in.nextInt(); in.nextLine();
        
        for(int a = 0; a < t; a++) {
            String s = in.nextLine();
            List<String> types = new ArrayList<String>();
            try {
                long e = Long.parseLong(s);
                types.add("long");
                int d = Integer.parseInt(s);
                types.add("int");
                short c = Short.parseShort(s);
                types.add("short");
                byte b = Byte.parseByte(s);
                types.add("byte");
                if(s.equals("1") || s.equals("0")) types.add("boolean");
            } catch(NumberFormatException exc) {
                
            } finally {
                if(types.size() == 0) System.out.println(s+" can't be fitted anywhere.");
                else {
                    System.out.println(s+" can be fitted in:");
                    for(int i = types.size()-1; i >= 0; i--) {
                        System.out.println("* "+types.get(i));
                    }
                }
            }
        }
    }
}