[英]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.