0

I just just had a phone interview and they asked me this question:

"What is the size of an integer, and, what is the equation to work this out?"

I had no idea (Ok, I'm a bit stupid) but it just intrigues me to find out the answer. My person guess was count up in base 2.. But I dunno.

Anyone have any ideas?

4

3 に答える 3

2

It seems like the question was asked to make you ask them:

  • What is the largest value that you want the integer type to encode?

Let's assume they said we want MAX_VALUE to be the maximum value an integer type can have.

This brings us to the equation. Since we are encoding it using bits we need log_2(MAX_VALUE) bits to encode any positive value of size up to MAX_VALUE. The logarithm of base 2 is there because with a bit pattern of size n you can encode up to 2^n different values. So if you want to know how long your maximum bit pattern needs to be to encode MAX_VALUE you need to calculate the log since:

2^(log_2(MAX_VALUE)) = MAX_VALUE

Now this is okay, unless you also want to encode the number 0. If you want to encode 0 as well then there are MAX_VALUE+1 numbers between 0 and MAX_VALUE so you need log_2(MAX_VALUE+1) bits to encode them all.

Another important question is what is the MIN_VALUE that we want to encode?

So in total you have MAX_VALUE + 1 + abs(MIN_VALUE) different values, so you will need :

bits_needed = log_2(MAX_VALUE + 1 + abs(MIN_VALUE))

As others have mentioned, in java int has max_value = 2,147,483,647 and min_value = -2,147,483,648. When you do the calculation you get log_2(4294967296) which is equal to 32. So 32 bits is the size of the integer type in java.

于 2012-11-05T18:34:46.200 に答える
0

The question is not clear, are you looking for integer bit-size for different programming languages? or you want to know the MAX value of int.

BTW, in java int is 32 bits and max is 2^31-1=2,147,483,647

于 2012-11-05T18:01:34.787 に答える
0

I think he asked for the range of integer. in Java, the size is 4 bytes, so should range from -2^31 to 2^31-1? Since he asked for the equation.

于 2012-11-05T18:10:28.143 に答える