在类里面,我们目前正在使用“顺时针”模函数 - 也就是说,该函数本质上与 Math.floorMod(int a, int b) 的工作方式相同。
对于类,我不能使用 Math.floorMod(),我在研究了这个主题后写了这个:
/**
* Computes {@code a} mod {@code b} as % should have been defined to work.
*
* @param a
* the number being reduced
* @param b
* the modulus
* @return the result of a mod b, which satisfies 0 <= {@code mod} < b
* @requires b > 0
* @ensures
*
* <pre>
* 0 <= mod and mod < b and
* there exists k: integer (a = k * b + mod)
* </pre>
*/
public static int mod(int a, int b) {
assert b > 0 : "Violation of: b > 0";
return (((a % b) + b) % b);
}
这是我的问题。该函数会传递我向其抛出的所有情况,但 a = 2 且 b = INTEGER.MAX_VALUE 的情况除外。
应该返回 2,就像 FloorMod 所做的那样,但它返回 0。无论如何,我可以在不使用 FloorMod 的情况下解决这个问题吗?
提前致谢。
最佳答案
((a % b) + b) // this does 2 + INTEGER.MAX and leads to an overflow
您可以使用以下方法来处理此问题并仍然保留 int 值:
public static int mod(int a, int b) {
assert b > 0 : "Violation of: b > 0";
return (int) (( (long) (a % b) + b) % b );
}
关于Java整数最大值测试与发条模数语句返回不正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32707213/