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?
It seems like the question was asked to make you ask them:
integertype to encode?Let’s assume they said we want
MAX_VALUEto 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 toMAX_VALUE. The logarithm of base 2 is there because with a bit pattern of sizenyou can encode up to2^ndifferent values. So if you want to know how long your maximum bit pattern needs to be to encodeMAX_VALUEyou need to calculate thelogsince: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_VALUEthat we want to encode?So in total you have
MAX_VALUE + 1 + abs(MIN_VALUE)different values, so you will need :As others have mentioned, in java
inthasmax_value = 2,147,483,647andmin_value = -2,147,483,648. When you do the calculation you getlog_2(4294967296)which is equal to 32. So 32 bits is the size of the integer type in java.