我正在研究 Date API 的 java 8 实现并发现了这个
Checks if the year is a leap year, according to the ISO proleptic calendar system rules.
This method applies the current rules for leap years across the whole time-line. In general, a year is a leap year if it is divisible by four without remainder. However, years divisible by 100, are not leap years, with the exception of years divisible by 400 which are.
For example, 1904 is a leap year it is divisible by 4. 1900 was not a leap year as it is divisible by 100, however 2000 was a leap year as it is divisible by 400.
The calculation is proleptic - applying the same rules into the far future and far past. This is historically inaccurate, but is correct for the ISO-8601 standard.
public boolean isLeapYear(long prolepticYear) {
return ((prolepticYear & 3) == 0) && ((prolepticYear % 100) != 0 || (prolepticYear % 400) == 0);
}
But give us prolepticYear & 3.
11111001111
&
00000000011
00000000011
prolepticYear & 3 是什么意思。
最佳答案
prolepticYear & 3
让我们稍微改变一下。 3
在二进制中是11
。因此,只有当 prolepticYear
的最后两位为零时,prolepticYear
& 11
才会为零。 (这实际上称为位掩码)。
现在想想也有点不同:
0100 - (4 in decimal, has last two bits zero)
1000 - (8 in decimal, has last two bits zero)
1100 - (12 in decimal, has last two bits zero)
... these are numbers divisible by four
通常 &
操作比 %
快。
有时 &
也用于其他目的(%
运算可能产生负数,而 &
会不是 - 这就是 HashMap
中的桶是如何根据 Key#hashcode
的可能负值来选择的,但这里不是这种情况)
关于Java 8 是闰年实现。逻辑运算符是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45165492/