在 Java 中,除以 1.6 的最快方法
·
除以 1.6 。从数学角度来说,x ÷ 1.6 = x ÷ 2 + x ÷ 8
可以用位运算来计算
BigInteger myBigInteger=new BigInteger("10");
myBigInteger.shiftRight(1).add(myBigInteger.shiftRight(3))
然后需要考虑舍入误差,因为数字右侧会损失一些位。需要考虑如何处理这些误差。
具体来说,如果原始数字的最后三位是 101 或 111,则此表达式“差一”。因此,更好的表达式应该是:
BigInteger myBigInteger=new BigInteger("10");
BigInteger result = myBigInteger.shiftRight(1).add(myBigInteger.shiftRight(3)).add(
BigInteger.valueOf(myBigInteger.testBit(0) && myBigInteger.testBit(2) ? 1 : 0));
System.out.println(result);
输出结果
更多推荐


所有评论(0)