[英]What is the simplest way to calculate the difference of two time stamps in java?
[英]What is the simplest way to calculate the amount of even numbers in a range in java
计算无符号整数范围内的偶数数量的最简单方法是什么?
例如:如果range为(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
这是一种方法:
从0到第一个数字的偶数为:
num_evens_first = (first/2 + 1)
从0到最后一个数字的偶数为:
num_evens_last = (last/2 + 1)
如果第一个数字本身是偶数,则该范围内的偶数就是这两个数字加1之间的差。 总而言之,您可以使用以下公式:
num_evens_last - num_evens_first + (first + 1)%2
或一次全部:
(last/2 + 1) - (first/2 + 1) + (first + 1)%2
简化:
last/2 - first/2 + (first + 1)%2
如果范围内的数字数量为偶数,则其中有n / 2个偶数。
如果是奇数,你有N / 2向下取整,如果first
是奇数和N / 2四舍五入,如果first
是偶数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.