Java 计算按传递金额分组

huangapple go评论60阅读模式
英文:

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);
}

huangapple
  • 本文由 发表于 2020年8月15日 13:12:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/63422806.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定