We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.

you will not be able to clear the test cases if u use that method because th range of because the range of int and long are very large to be inputted xplicitly like if u enter 2147483648 which is the rangeof int is verylarge value for compiler

(int) Math.pow(2, 31) casting would be done before the subtraction I believe. Do you need to cast?
also, you really don't need to check for long. Any value not throwing an exception will fit.

I think for loop is troubling everyone here (including me ). For loop limit should be the first int we are taking . Its just not any random number, its actually the number of inputs which different test cases gonna have.

use (short)(Math.pow(2,15)-1) instead of (short) Math.pow(2,15) -1 because:

The value of Math.pow(2,15) = 32768.0 ,when you type cast it to short its value becomes -32768 and when you subtract it from 1 the value is -32769 .So,first subtract 1 from the Math.pow(2,15) then type cast to short.The same logic for the int and long.

if (x >= Short.MIN_VALUE && x <= Short.MAX_VALUE) System.out.println("* short");
if (x >= Integer.MIN_VALUE && x <= Integer.MAX_VALUE) System.out.println("* int");
if (x >= Long.MIN_VALUE && x <= Long.MAX_VALUE) System.out.println("* long");

any of the data type has a specific range.
take byte!
its range is from -128 to 127;
if you raise - 2 to the power of 7 i.e. -128. (this number is in the required range!).
but if you raise 2 to the power of 7 i.e. 128. (this number is not in the required range(127)). So, all you need is subtract 1 from 128 and hence the code :

long 64 –9,223,372,036,854,775,808 to
9 ,223,372,036,854,775,807

int 32 –2,147,483,648 to
2,147,483,647

short 16 –32,768 to
32,767

byte 8 –128 to
127

if you recognize the positive number of the primitive variable is alway less with 1, check the Byte the minimum is -128 and the positive is not 128, its 128 -1 = 127, so we add -1 so we can have the right positive range and have the right value.
wish i was helpfull

Thanks for your reply.
I'm aware of the data type ranges.
Simply just inserting the ranges within an if statements isn't enough and doesn't pass you the test cases 3 & 4.

Nevertheless, I've managed to solve the challenge! :D

hey dear Smiriti there is no need math.pow() fuction as u can see there is long in all cases except can't fitted else condition so use simply this code
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");
if(x>=-32768 && x<=32767)System.out.println("* short");
if(x>=-2147483648 && x<=2147483647)System.out.println("* int");
System.out.println("* long");
//Complete the code
}
catch(Exception e)
{
System.out.println(sc.next()+" can't be fitted anywhere.");
}
}
}

I just have one silly question. Say we are doing for short then I wanted to know why we are doing Math.pow(2,15) and not Math.pow(2,16) considering we want 2 to the power of 16 and not 15.

int is greater than short and byte only. If we take an int variable, that can also be used to store even byte value and also short value bcoze int is bigger than short and byte. like that if we take a long, that can be used to compare with any of byte, short, int.

I tired to do the same but got wrong answer for test case 2 and 3.

long x=sc.nextLong();
System.out.println(x+" can be fitted in:");
if(x >=(short)Short.MIN_VALUE && x <=(short)Short.MAX_VALUE)
System.out.println("* short");
if(x >=(int)Integer.MIN_VALUE && x <=(int)Integer.MAX_VALUE)
System.out.println("* int");
if(x >=(long)Long.MIN_VALUE && x <=(long)Long.MAX_VALUE)
System.out.println("* long");

The return you get from Math.pow is in doubleand you're comparing it with x i.e.long. Can we do it? Don't you think there's flaw here? If no! Could you please explain why? Using MIN and MAX is the best option I suppose.

instead of if(x>=-32768 && x<=32768)
try if(x >= -32768 && x <= 32767)
I think it's because 0 counts and a bit so the range ends at 32767 instead of 32768

i think its related to priority
x>=-128 && x<=127
we havent write it as
x>=-128 && x<=128-1
the reason is <= operator has greater priority then -(minus)

Kucao's solution is NOT exactly correct.
What if the input is number = 10.
Number 10 can be fit into ANY primitive type. So, every single "if" in Kucao's code will be duplicated in the output.

Better to use if-else if construct. Like this

longx=sc.nextLong();System.out.println(x+" can be fitted in:");if(x>=-128&&x<=127)System.out.println("* byte\n* short\n* int\n* long");elseif(x>=((-1)*(Math.pow(2,15)))&&x<=((Math.pow(2,15)-1)))System.out.println("* short\n* int\n* long");elseif(x>=((-1)*(Math.pow(2,31)))&&x<=((Math.pow(2,31)-1)))System.out.println("* int\n* long");elseif(x>=((-1)*(Math.pow(2,63)))&&x<=((Math.pow(2,63)-1)))System.out.println("* long");

In your solution Math.pow(2,63) is actually going to return an Int, it will return the largest int it can be calculated (2^31)-1. You have to specifically point out which numbers are going to be considered longs by appending an L at the end of the number (Like this: 600851475143L). This is because in java long literals end with an L. Source

I have almost the same solution as you, with the exception that I have every max and min dataType value stored in a different variable (like minInt, maxInt, minShort and so on).

Even though, I cant get it right on the test scenarios once the solution is submitted. Its quite frustrating.

Instead of wasting your time and resources doing mathematical calculations, you should just use final static values that are kept in classes. For example classes Byte, Short, Int, Long have final static variables for their MIN_VALUE and MAX_VALUE. So you can write your program like this to make it much more efficient. Don't forget, we are computer engineers. Engineer is a person who solves problem and solved problems efficiently. Solving a problem alone is not engineering.

Some of the other comments already mentioned it, but basically the nextLong() token threw an error, so reading the same token with next() allows us to repeat the token as part of the error message.

if you entered the catch block, an exception has been raised.

most surely, the exception is due to the statement

long x=sc.nextLong();

Hence, you cannot use nextLong() to obtain that large a number.

A different way to obtain this number is to use next(). This function returns the next token as a String (in other words, as is). Since every input is a valid String, this function will not fail and will surely give you the next token (the token you failed to obtain using nextLong()).

I think it is very unnecessary to check if it fits into long. We have x variable in long datatype in the beginning, and also if it fits byte, short and int all the way, it'll definitely fit in long. So you can just print that it fits into long, without checking.

P.S. Why doesn't HackerRank have code formatting?..

You actually don't need the last if statement in your code.

The variable 'x' is initialized as a long. If it initializes successfully, then we already know it fits in long. If it doesn't fit in long, an exception will be thrown at the initialization statement, prompting the catch statement which prints out that it can't be fitted anywhere.

## Java Datatypes

You are viewing a single comment's thread. Return to all comments →

class Solution{ public static void main(String []argh) {

}

Hey Kucao, I had the same solution as yours, with just this minor change, and I got it wrong. Not able to understand why. Can someone explain ?

casting will truncate value

but here it every casting is in range its range we are dealing with int types so where comes the question of casting

That messed me up. I casted and was not able to get the as long value. Once I remove it worked.

We do not need to cast explicitly. We are just required to check the applicable ranges.

i tried using appying the range directly but i couldnt able to clear two test cases

which?

u added pow function but i tried with entering the range values like for byte -128 to 127 but i am not able to clear the 2 testcases among 4

same here, could u help.

you will not be able to clear the test cases if u use that method because th range of because the range of int and long are very large to be inputted xplicitly like if u enter 2147483648 which is the rangeof int is verylarge value for compiler

I meant something like Byte.Max() which does not require any literal number to be input but will always be dependant on the compiler...

You must have used if(x>=-Math.pow(2,31) && x=-Math.pow(2,31) && x<= Math.pow(2,31)-1 ) and also for long ""x<=Math.pow(2,63)-1""

but then..i thnk this wont work?

Thanks...

Casting is necessary because Math.pow function returns value in double

(int) Math.pow(2, 31) casting would be done before the subtraction I believe.

Do you need to cast?

also, you really don't need to check for long. Any value not throwing an exception will fit.

use x<= (short) (Math.pow(2,15)-1.0)

Simply write your own 2^x function and use that instead of Math.pow which has an upper limit:

Nice

also failed testcase 2 and 3

yes Im too facing same problem.

Most programming languages have a way of finding the maximum and minimum of number data types, how about exploring that option?

I think for loop is troubling everyone here (including me ). For loop limit should be the first int we are taking . Its just not any random number, its actually the number of inputs which different test cases gonna have.

same here

same

use (short)(Math.pow(2,15)-1) instead of (short) Math.pow(2,15) -1 because:

The value of Math.pow(2,15) = 32768.0 ,when you type cast it to short its value becomes -32768 and when you subtract it from 1 the value is -32769 .So,first subtract 1 from the Math.pow(2,15) then type cast to short.The same logic for the int and long.

Agreed. That makes sense.

not running

if (x >= Short.MIN_VALUE && x <= Short.MAX_VALUE) System.out.println("* short"); if (x >= Integer.MIN_VALUE && x <= Integer.MAX_VALUE) System.out.println("* int"); if (x >= Long.MIN_VALUE && x <= Long.MAX_VALUE) System.out.println("* long");

no no impossible

We can reply a redundant condition check through the below mentioned code:

try{ long x=sc.nextLong(); System.out.println(x+" can be fitted in:"); if(x>=Byte.MIN_VALUE && x<=Byte.MAX_VALUE)System.out.println("* byte\n* short\n* int\n* long"); else if(x>=Short.MIN_VALUE && x<=Short.MAX_VALUE)System.out.println("* short\n* int\n* long"); else if(x>=Integer.MIN_VALUE && x<=Integer.MAX_VALUE)System.out.println("* int\n* long"); else System.out.println("* long"); }catch(Exception ex){ System.out.println(sc.next()+" can't be fitted anywhere."); }

hey, @srikanthdikalla i had the same solution as your's but its not working ,gives compilation error can anyone please explain this?

if(x>=Byte.MIN_VALUE && x<=Byte.MAX_VALUE) System.out.println("* byte"); if(x>=Short.MIN_VALUE && x<=Short.MAX_VALUE) System.out.println("* int"); if(x>=Integer.MIN_VALUE && x<=Integer.MAX_VALUE) System.out.println("* short"); if(x>=Long.MIN_VALUE && x<=Long.MAX_VALUE) System.out.println("* long"); }

Why are we including -1 at the end. can anyone explain me?

noo

because of range

can you explain it clearly please

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

any of the data type has a specific range. take byte! its range is from -128 to 127; if you raise - 2 to the power of 7 i.e. -128. (this number is in the required range!). but if you raise 2 to the power of 7 i.e. 128. (this number is not in the required range(127)). So, all you need is subtract 1 from 128 and hence the code :

bacause, like byte range is 8 so last in 0 to 7 meanse 8-1=7 hope you got it

It's to do with the range that data type can have.

For example short can have minimum -32,768 to maximum of 32,767.

Same case for int & long, which is ONE less number for it's maximum.

It's easier to write (2^31 - 1) than it is to write 2147483648 - 1 = 2147483647

long 64 –9,223,372,036,854,775,808 to 9 ,223,372,036,854,775,807

int 32 –2,147,483,648 to 2,147,483,647

short 16 –32,768 to 32,767

byte 8 –128 to 127

Thanks for your reply. I'm aware of the data type ranges. Simply just inserting the ranges within an if statements isn't enough and doesn't pass you the test cases 3 & 4.

Nevertheless, I've managed to solve the challenge! :D

Because in range of every databytes from negative to positive(postive is (-1) less than to negative ) as in byte -128 to +127.

If first if condition work then no other if will work.

(short)-Math.pow(2, 15)What is the use of minus sign '-' there???short range of value lie to (-2 ^15 to 2^15-1)

According to problem statement the long data type can fit in all possibe input except when it doesnt. So the initialization and assignment part

yes when we are checking that condition ,two of the four testcases are being failed. Can u explain the rsn?

hey,kinara.....please explain me the needs for type casting every Math.pow().....??

yes here's need of this function

hey dear Smiriti there is no need math.pow() fuction as u can see there is long in all cases except can't fitted else condition so use simply this code import java.util.

; import java.io.;class Solution{ public static void main(String []argh) {

}

I just have one silly question. Say we are doing for short then I wanted to know why we are doing Math.pow(2,15) and not Math.pow(2,16) considering we want 2 to the power of 16 and not 15.

this is impisive casting of primitive types.that happen automatically.compiler does it when ever requary.

hey kucao,why did you converted the int number to long?what is the need of doing that?please reply.

int is greater than short and byte only. If we take an int variable, that can also be used to store even byte value and also short value bcoze int is bigger than short and byte. like that if we take a long, that can be used to compare with any of byte, short, int.

reply

I solved it by using Datatype.MAX_VALUE; DataType.MIN_VALUE; ex. Long.MAX_VALUE;

Which might not be the point of the exercise, but I think it's really robust code.

This really is the best way to accomplish this task.

what method should i use

Not method, but constant MIN_VALUE or MAX_VALUE od each type; e.g. for int you can use Integer.MIN_VALUE and Integer.MAX_VALUE.

I believe, the idea was to "solve" proving that you "know" what the MIN and MAX are. Not, using the library constant.

all in one

no no its waste

I did it the same way! ran only the sample test others were wrong

I tired to do the same but got wrong answer for test case 2 and 3.

long x=sc.nextLong(); System.out.println(x+" can be fitted in:"); if(x >=(short)Short.MIN_VALUE && x <=(short)Short.MAX_VALUE) System.out.println("* short"); if(x >=(int)Integer.MIN_VALUE && x <=(int)Integer.MAX_VALUE) System.out.println("* int"); if(x >=(long)Long.MIN_VALUE && x <=(long)Long.MAX_VALUE) System.out.println("* long");

if(x>=Byte.MIN_VALUE && x<=Byte.MAX_VALUE) System.out.println("* byte"); if(x>=Short.MIN_VALUE && x<=Short.MAX_VALUE) System.out.println("* short"); if(x>=Integer.MIN_VALUE && x<=Integer.MAX_VALUE) System.out.println("* int"); if(x>=Long.MIN_VALUE && x<=Long.MAX_VALUE) System.out.println("* long"); }

if(x>=Byte.MIN_VALUE && x<=Byte.MAX_VALUE) System.out.println("* byte"); if(x>=Short.MIN_VALUE && x<=Short.MAX_VALUE) System.out.println("* short"); if(x>=Integer.MIN_VALUE && x<=Integer.MAX_VALUE) System.out.println("* int"); if(x>=Long.MIN_VALUE && x<=Long.MAX_VALUE) System.out.println("* long"); } using Wrapper Class we can solve it.

thanks this one is helpful

It worked

I liked this, I used: Byte.MIN_VALUE, Byte.MAX_VALUE Short.MIN_VALUE, Short.MAX_VALUE Integer.MIN_VALUE, Integer.MAX_VALUE

Thanks for sharing jgj_io

You're welcome. Keep at it.

Can you tell me what does the -1 do in the if statement?

If you are still curious about this now, it accounts for 0.

am i

it does what it doos

The range of byte is (2^7) to (2^7)-1. ie -128 to 127

Hey Shafaet, I had some masking techique that can not using any library but am not implemented it,

A&0=0

The return you get from Math.pow is in doubleand you're comparing it with x i.e.long. Can we do it? Don't you think there's flaw here? If no! Could you please explain why? Using MIN and MAX is the best option I suppose.

can you please tell me why we want to use -1 ??

because one of the value is zero. to adjust that !

short range is from -32768 to 32767 but not from -32768 to 32767 so we use '-1' in Math.pow(2,15)

What's the difference between -32768 to 32767 and -32768 to 32767

the difference is in th question

hey Kucao, With the help of this code i creared only Test case #0. for other test case it is wrong. Can you please help me.

I had the same solution. But i wasnt able to run it. System said it is a worng answer. Can someone please explain? Thanks!

explain

thanks

welcome

i have written the same code but it shows error in last two testcases

me too

u did it wrong

why is

Different from:

I tried the first one since its the value given by java documentation but it doesn't work on the last two test cases. can anyone please tell me..

I also have same problem .. and till now didn't understand .. so please any'ne can explain me

instead of if(x>=-32768 && x<=32768) try if(x >= -32768 && x <= 32767) I think it's because 0 counts and a bit so the range ends at 32767 instead of 32768

yes

short range is from -32768 to 32767 but not from -32768 to 32767

i think its related to priority x>=-128 && x<=127 we havent write it as x>=-128 && x<=128-1 the reason is <= operator has greater priority then -(minus)

plz explain this solution

noo

why sc.next() is used in catch??? why cant we use x instead ?

i dont know

Thanks.. It helped!

fake

what about test case -100000000000000000??? it's not work???

try this :- long num2 = (long)Math.pow((double)2,(double)63); long x = sc.nextLong(); ...... ...... if(x>=-m2 && x<=m2-1)System.out.println("* long");

yes

can you please tell what

sc.next()does?.next method reads the next token of input

no

please explain how sc.next() working outside the try{}. System.out.println(sc.next()+" can't be fitted anywhere.");

i entered the actual values in test cases. It threw error for the value 9223372036854775807 saying that it can't store that number for long.

Add an L at the end -- 9223372036854775807L -- specifies a comparison with the long type

@kucao why you had writeen "can't be fitted anywhere" in catch block which exception will be thrown for this?

can you please explain me this code ?

i'm unable to submit this above code as well don't understand why

hye.can someone explain what is the meaning of -Math.pow(2,15) and when we need to use -Math.pow?and also the function of -Math.pow.tq

why compiler showing error out of range if(x>=-9223372036854775808 && x<= 9223372036854775807) as 9223372036854775807 is the range of long

For long value you must put 'L'after the value.(use 9223372036854775807L)

yes

why we use try?

Kucao, and all

Kucao's solution is NOT exactly correct. What if the input is number = 10. Number 10 can be fit into ANY primitive type. So, every single "if" in Kucao's code will be duplicated in the output.

Better to use if-else if construct. Like this

Not working for Cases #2 and #3

you write exact value for 2^63 & 2^31,and it will work.

Here its works class Solution{ public static void main(String []argh) {

}

U don't need -1 at the end of each code result still is same

In your solution Math.pow(2,63) is actually going to return an Int, it will return the largest int it can be calculated (2^31)-1. You have to specifically point out which numbers are going to be considered longs by appending an L at the end of the number (Like this: 600851475143L). This is because in java long literals end with an L. Source

I have almost the same solution as you, with the exception that I have every max and min dataType value stored in a different variable (like minInt, maxInt, minShort and so on).

Even though, I cant get it right on the test scenarios once the solution is submitted. Its quite frustrating.

Instead of wasting your time and resources doing mathematical calculations, you should just use final static values that are kept in classes. For example classes Byte, Short, Int, Long have final static variables for their MIN_VALUE and MAX_VALUE. So you can write your program like this to make it much more efficient. Don't forget, we are computer engineers. Engineer is a person who solves problem and solved problems efficiently. Solving a problem alone is not engineering.

thank you MichaelWittmann this worked, great.

in the following line of code: "System.out.println(sc.next()+" can't be fitted anywhere.");",instead of "sc.next",Why can't we write "sc.nextLong"?

Some of the other comments already mentioned it, but basically the nextLong() token threw an error, so reading the same token with next() allows us to repeat the token as part of the error message.

This solution is giving 2 testcases wrong. What is the problem? Can anyone please explain ?

}

All test cases have been passedThere is

only one wrong in your code, you just make the last test case as if(x>=Math.pow(-2,63) && x<=Math.pow(2,63)).You basically needed to add an equal there, else it wont work.Hope this helpsIt will work fine

}

WHY WE USE SC.NEXT() IN CATCH PLS EXPLAIN!

if you entered the catch block, an exception has been raised.

most surely, the exception is due to the statement

Hence, you cannot use nextLong() to obtain that large a number.

A different way to obtain this number is to use next(). This function returns the next token as a String (in other words, as is). Since every input is a valid String, this function will not fail and will surely give you the next token (the token you failed to obtain using nextLong()).

Cool

can someone explain this code.please

I think it is

veryunnecessary to check if it fits into long. We have x variable in long datatype in the beginning, and also if it fits byte, short and int all the way, it'll definitely fit in long. So you can just print that it fits into long, without checking.P.S. Why doesn't HackerRank have code formatting?..

Can we use range instead of Math.pow()?How Math.pow() working?

Instead of

You could write this:

Without "=" and "-1"

is it ok continous if without else?

yes

long x = sc.nextLong(); System.out.println(x + " can be fitted in:");

Why can't we use the ranges directly instead of Math.pow. For example,instead of MAth.pow(2,31)why can't we use 32,768

You actually don't need the last if statement in your code.

The variable 'x' is initialized as a long. If it initializes successfully, then we already know it fits in long. If it doesn't fit in long, an exception will be thrown at the initialization statement, prompting the catch statement which prints out that it can't be fitted anywhere.

Hello I can't understand your code so pls explain your code!!

I just wrote the ranges for each data type and then simply compared with the given input

Great code. Thanks for sharing.