感谢回复。到目前为止,我只有在原始解决方案上取得了成功,但我仍然希望看到更好的东西。这是一个简单的测试类,我建立它来尝试帮助促进想法:
package com.scratch;
import java.util.ArrayList;
import java.util.List;
public class Test {
private static class Values {
long x;
long y;
long result;
Values(long x, long y, long result) {
this.x = x;
this.y = y;
this.result = result;
}
}
public static void main(String[] args) {
List<Values> list = new ArrayList<Values>();
Values v1 = new Values(18, 3, 18);
list.add(v1);
Values v2 = new Values(18, 5, 20);
list.add(v2);
Values v3 = new Values(121, 25, 125);
list.add(v3);
Values v4 = new Values(9999999, 10, 10000000);
list.add(v4);
Operation operation = new MyFormula();
for (Values v : list) {
System.out.println(v.x + ", " + v.y + " => " + v.result + "?");
long res = operation.perform(v.x, v.y);
System.out.println(res == v.result ? "worked" : "nope... Expected "
+ v.result + ", got " + res);
}
}
private static interface Operation {
long perform(long x, long y);
}
private static class MyFormula implements Operation {
@Override
public long perform(long x, long y) {
return x - ((x % y) == 0 ? y : x % y) + y;
}
}
private static class RecommendedFormula implements Operation {
@Override
public long perform(long x, long y) {
return (long) (Math.ceil(x / y) * y);
}
}
private static class RecommendedFormula2 implements Operation{
@Override
public long perform(long x, long y) {
return x + (y - x % y) % y;
}
}
}
我的公式(在问题中)似乎工作得很好。 推荐的公式不行,但可能只是因为我使用了不同的类型(这是我在最终产品中需要使用的类型)。