Define the n-based integer rounding of an integer k to be the nearest multiple of n to k. If two multiples of n are equidistant use the greater one.
the 4-based rounding of 5 is 4 because 5 is closer to 4 than it is to 8,
the 5-based rounding of 5 is 5 because 5 is closer to 5 that it is to 10,
the 4-based rounding of 6 is 8 because 6 is equidistant from 4 and 8, so the greater one is used
Write a function named doIntegerBasedRounding that takes an integer array and rounds all its positive elements using n-based integer rounding. A negative element of the array is not modified and if n <=0, no elements of the array are modified. Finally you may assume that the array has at least two elements.
我在两个案例中面临的问题
({1, 2, 3, 4, 5},2) and ({-18, 1, 2, 3, 4, 5},4)
我得到了
[0, 2, 2, 4, 4] and [-18, 0, 0, 4, 4, 4]
代替
{2, 2, 4, 4, 6} and {-18, 0, 4, 4, 4, 4}
这是我的代码
class doIntegerBasedRounding {
public static void main(String[] args) {
System.out.println(Arrays.toString(doIntegerBasedRounding(new int []{1,2,4,5,6,7,8,9,9},5)));
System.out.println(Arrays.toString(doIntegerBasedRounding(new int []{1, 2, 3, 4, 5},2)));
System.out.println(Arrays.toString(doIntegerBasedRounding(new int []{1, 2, 3, 4, 5},3)));
System.out.println(Arrays.toString(doIntegerBasedRounding(new int []{1, 2, 3, 4, 5},-3)));
System.out.println(Arrays.toString(doIntegerBasedRounding(new int []{-1, -2, -3, -4, -5},3)));
System.out.println(Arrays.toString(doIntegerBasedRounding(new int []{-18, 1, 2, 3, 4, 5},4)));
System.out.println(Arrays.toString(doIntegerBasedRounding(new int []{1, 2, 3, 4, 5},5)));
System.out.println(Arrays.toString(doIntegerBasedRounding(new int []{1, 2, 3, 4, 5},100)));
}
public static int[] doIntegerBasedRounding(int[]a, int n){
int temp;
int[] b= new int[a.length];
if(n<0)
return a;
for (int i =0; i<a.length; i++){
if(a[i]<=0){
b[i]=a[i];
}
else if(a[i]>0) {
temp = a[i]%n;
if(temp>n/2) {
b[i] = a[i] + (n - temp);}
if (temp<=n/2){
b[i]= a[i]-temp;
}
}
}
return b;
}
}
最佳答案
让我建议一个不同的方法:
调用你正在使用的值v
:
- 计算
v
除以n
的余数 - 从
v
中减去这个余数;这导致四舍五入 - 如果余数等于或大于
n/2
,则添加n
;这导致四舍五入。
在代码中,针对您的特定问题结构:
public void doIntegerBasedRounding(int[] values, int n)
{
if (n > 0)
{
for (int i=0; i<values.length; i++)
{
if (values[i] > 0)
{
int rem = values[i]%n;
values[i] = values[i] - rem + (rem>=n/2 ? n : 0);
}
}
}
}
关于java - 基于整数的舍入问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38546840/