值与区域匹配,
0 -> [0,60)
100 -> [60,120)
200 -> [120,180)
...
如果我有一个值 160,程序应该返回 200,因为 160 在 (120, 180) 中。
有什么快速的方法吗?
最好用Java来描述。
谢谢。
更新:
1.可能有大量的结果标签,像这样:
0, 1, 2 , ... 我 ..., (i++)
2.区域范围并不总是增加60。
[0, 60)
[60, 100)
...
最佳答案
对于长度相等的区域,您可以指定与数组中的区域对应的结果值,并根据输入值计算数组索引,如下所示:
public class Example {
private static final int[] MAPPING = {0, 100, 200};
private static final int REGION_LENGTH = 60;
public static int encode(int value) {
// TODO apply range check to avoid ArrayIndexOutOfBounds
return MAPPING[(value / REGION_LENGTH)];
}
public static void main(String[] args) {
System.out.println(encode(160)); // prints 200
}
}
关于java - 如何通过给定值在一个区域中获取特殊值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22421676/