@echo off
setlocal
set /P "year=Enter year: "
set /A "leap=!(year%%4) + (!!(year%%100)-!!(year%%400))"
if %leap% equ 1 echo Is leap year
Accordingly to Wikipedia a year is leap if it is divisible by 4 excepting if it is also divisible by 100, in which case it is leap only if it is also divisible by 400 ("divisible" means that the remainder of the division by the given number is zero). This way, 2000 and 2400 are leap years because their remainders when they are divided by 400 are zero, but 2100, 2200 and 2300 are not: these are special cases because their remainders when they are divided by 100 are zero.
In set /A
command the !
boolean NOT operator gives 1 if its operand is zero and gives 0 in any other case, so set /A "leap=!(year%%4)"
gives 1 if the year is divisible by 4 and zero in any other case; this gives the first part of the result.
After that we need to subtract 1 from this value in years 2100, 2200 and 2300, but subtract nothing in years 2000 and 2400; that is:
year year%%100 a=!!(year%%100) year%%400 b=!!(year%%400) a-b
2000 0 0 0 0 0
2100 0 0 100 1 -1
2200 0 0 200 1 -1
2300 0 0 300 1 -1
2400 0 0 0 0 0
If the year is not divisible by 100 then both a
and b
values are equal to 1, so a-b
is zero and the result is given just by the original remainder by 4.
This way, the formula set /A "leap=!(year%%4) + (!!(year%%100)-!!(year%%400))"
gives the complete result.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…