为什么以下两个操作在 Java 中对于 x = 31
或 32
产生不同的结果,而对于 x=3
产生相同的结果?
int x=3;
int b = (int) Math.pow(2,x);
int c = 1<<x;
结果:
x=32: b=2147483647; c=1;
x=31: b=2147483647; c=-2147483648;
x=3: b=8 ; c=8
最佳答案
有多个问题在起作用:
- 安
int
只能存储-2147483648
之间的值和2147483647
. -
1 << x
只有 uses the lowest five bits ofx
.因此,1 << 32
根据定义与1 << 0
相同. - Shift 操作在 two's-complement integer representation of the value of the left operand 上执行;这解释了为什么
1 << 31
是负面的。 -
Math.pow(2, 32)
返回double
. -
(int)(d)
, 其中d
是double
大于2147483647
返回2147483647
("the largest representable value of typeint
")。
这个面试题的作用是表明 (int)Math.pow(2, x)
和 1 << x
不等于 x
的值外面0
... 30
范围。
附言可能有趣的是,使用 long
代替 int
(和 1L
代替 1
)会给出另一组不同于其他两个的结果。即使最终结果转换为 int
也是如此。 .
关于(int)Math.pow(2,x) 和 1<<x 的 Java 结果不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10416694/