2 views
in Java

In a coding test I have submitted the following code:

import java.util.*;

import java.io.*;

class Solution{

public static void main(String []args)

{

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>=(long)-128 && x<=(long)127)System.out.println("* byte");

if(x>=-1*(long)Math.pow(2,15) && x<=(long)Math.pow(2,15)-1)System.out.println("* short");

if(x>=-1*(long)Math.pow(2,31) && x<=(long)Math.pow(2,31)-1)System.out.println("* int");

if(x>=-1*(long)Math.pow(2,63) && x<=(long)Math.pow(2,63)-1)System.out.println("* long");

}

catch(Exception e)

{

System.out.println(sc.next()+" can't be fitted anywhere.");

}

}

}

}

It fails some test cases.

This is one of the test cases that do not pass

17 9223372036854775808 9223372036854775807 -9223372036854775808 -9223372036854775807 4294967296 4294967295 -4294967296 -4294967295 65536 65535 -65536 -65535 256 255 -256 -255 12222222222222222222222222222222222222222221

Can someone tell me what the problem is?

by (13.1k points)

The problem is with Math.pow(2,63). The Math.pow returns a double when the cast occurs maybe you can lose some information.

If you want that ‘if’ will work, if( x >= -1 * (long) Math.pow(2,63) && x<=(long) Math.pow(2,63) -1 ) System.out.println("* long");

You need to add a bracket, like  x<=(long) ( Math.pow(2,63)-1 )

if(x>=-1*(long)Math.pow(2,63) && x<=(long) ( Math.pow(2,63)-1 ) )System.out.println("* long");

Want to learn Java? Check out the Java certification from Intellipaat.