例.
int a = 254;
int b = 25;
int c = (closest integer to `a` that is divisible by `b`)
Run Code Online (Sandbox Code Playgroud)
我怎样才能找到整数c?这个例子的结果是c = 250.
And*_*ira 15
有两种情况需要考虑:
最接近的整数小于或等于a:
int c1 = a - (a % b);
Run Code Online (Sandbox Code Playgroud)最接近的整数大于a:
int c2 = (a + b) - (a % b);
Run Code Online (Sandbox Code Playgroud)然后我们需要检查哪个更接近a并返回:
int c;
if (a - c1 > c2 - a) {
c = c2;
} else {
c = c1;
}
Run Code Online (Sandbox Code Playgroud)
所以我们可以创建一个closestInteger()这样的方法:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
例:
System.out.println(closestInteger(254, 25));
System.out.println(closestInteger(9, 5));
Run Code Online (Sandbox Code Playgroud)
输出:
250
10
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2339 次 |
| 最近记录: |