计算无符号整数范围内偶数数量的最简单方法是什么?
示例:如果范围为 (0,4),则应返回 3。
我很难想出任何简单的方法。我想到的唯一解决方案涉及几个 if 语句。是否有一行简单的代码可以在没有 if 语句或三元运算符的情况下完成此操作。
public static int countEvens(int first, int last)
{
int count = 0;
for(int i = first; i <= last; i++)
count += i%2 == 0 ? 1 : 0;
return count;
}
这行得通吗?
最佳答案
你需要
last / 2 - (first + 1) / 2 + 1
关于java - java中计算某个范围内偶数数量的最简单方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20528623/