英文:
Java calculate group by passed amount
问题
以下是翻译好的代码部分:
if(points > 1000000) {
return 9;
}
if (points > 400000) {
return 8;
}
if (points > 100000) {
return 7;
}
if (points > 20000) {
return 6;
}
if (points > 5000) {
return 5;
}
if(points > 1000) {
return 4;
}
if(points > 250) {
return 3;
}
if(points > 25) {
return 2;
}
if(points > 10) {
return 1;
}
return 0;
希望这有助于你优化你的项目!
英文:
I am optimizing my old project and I'm not sure what's the best way to optimize the code below, basically, this code determines groupId (return value), by a number of points that user has, is there any better way of returning this number under those circumstances?
My Code:
if(points > 1000000) {
return 9;
}
if (points > 400000) {
return 8;
}
if (points > 100000) {
return 7;
}
if (points > 20000) {
return 6;
}
if (points > 5000) {
return 5;
}
if(points > 1000) {
return 4;
}
if(points > 250) {
return 3;
}
if(points > 25) {
return 2;
}
if(points > 10) {
return 1;
}
return 0;
}
答案1
得分: 1
你可以像这样使用 Arrays.binarySearch(int[] a, int key)
:
private static final int[] LEVELS = { 10, 25, 250, 1000, 5000, 20000, 100000, 400000, 1000000 };
static int determineGroup(int points) {
int group = Arrays.binarySearch(LEVELS, points);
return (group >= 0 ? group : -group - 1);
}
英文:
You can use Arrays.binarySearch(int[] a, int key)
like this:
private static final int[] LEVELS = { 10, 25, 250, 1000, 5000, 20000, 100000, 400000, 1000000 };
static int determineGroup(int points) {
int group = Arrays.binarySearch(LEVELS, points);
return (group >= 0 ? group : -group - 1);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论