Why do the following two operations yield different results in Java for x = 31 or 32 but the same results for x=3?
int x=3;
int b = (int) Math.pow(2,x);
int c = 1<<x;
Results:
x=32: b=2147483647; c=1;
x=31: b=2147483647; c=-2147483648;
x=3: b=8 ; c=8
There are multiple issues at play:
intcan only store values between-2147483648and2147483647.1 << xonly uses the lowest five bits ofx. Thus,1 << 32is by definition the same as1 << 0.1 << 31is negative.Math.pow(2, 32)returns adouble.(int)(d), wheredis adoublegreater than2147483647returns2147483647(“the largest representable value of typeint“).What this interview question does is show that
(int)Math.pow(2, x)and1 << xare not equivalent for values ofxoutside the0…30range.P.S. It is perhaps interesting to note that using
longin place ofint(and1Lin place of1) would give yet another set of results different from the other two. This holds even if the final results are converted toint.