Someone on JSPerf dropped an amazingly fast implementation for checking leap years of the ISO calendar (link: Odd bit manipulations):
function isLeapYear(year) {
return !(year & 3 || year & 15 && !(year % 25));
}
Using Node.js, I quickly checked it against two other one-liner implementations I know.
function isLeapClassic(y) { return (y % 4 == 0) && !(y % 100 == 0) || (y % 400 == 0); }
function isLeapXOR(y) { return (y % 4 == 0) ^ (y % 100 == 0) ^ (y % 400 == 0); }
function isLeapBitwise(y) { return !(y & 3 || y & 15 && !(y % 25)); }
//quick'n'dirty test on a small range!
//works with negative integers too
for (var i = 1900; i <= 2100; i++) {
console.log(
"year = %d,\t%d%d%d",
i,
isLeapClassic(i),
isLeapXOR(i),
isLeapBitwise(i)
);
}
It works as expected, but my problem is I can't figure how.
I know ((a % b) == (a & (b-1))
when b is power of two so (year % 4) == (year & 3)
, but year & 15 && !(year % 25)
is quite hard to figure out. Can someone explain me how it works? Any reference about this implementation?