例.
int a = 254; int b = 25; int c = (closest integer to `a` that is divisible by `b`)
我怎样才能找到整数c?该示例的结果是c = 250.
解决方法
有两种情况需要考虑:
>最接近的小于或等于a的整数:
int c1 = a - (a % b);
>最接近的整数大于a:
int c2 = (a + b) - (a % b);
然后我们需要检查哪个更靠近a并返回:
int c; if (a - c1 > c2 - a) { c = c2; } else { c = c1; }
所以我们可以像这样创建一个nearestInteger()方法:
static int closestInteger(int a,int b) { int c1 = a - (a % b); int c2 = (a + b) - (a % b); if (a - c1 > c2 - a) { return c2; } else { return c1; } }
例:
System.out.println(closestInteger(254,25)); System.out.println(closestInteger(9,5));
输出:
250 10