How to check if the given year is a leap year, without using division operation or some library method in Java. Is it possible to check this using a bitwise operator?
PS: validation not necessary for centuries
How to check if the given year is a leap year, without using division operation or some library method in Java. Is it possible to check this using a bitwise operator?
PS: validation not necessary for centuries
Here are some ways of identifying leap years without using a modulo function.
Firstly, let’s assume (or test) that the year is in the range 1901 - 2099
.
A leap year expressed as a binary number will have 00
as the
last two digits. So:
it’s a leap year if year & (not 4) == 0
If you have a function available to truncate a real number to an integer then this works:
x = trunc(year / 4)
it’s a leap year if x * 4 == year
If you have shift (not circular shift) operators, which I’m sure Verilog has then:
x = year >> 2
it’s a leap year if (x << 2) == year
If the assumption about the range being 1901 - 2099
is false then you’ll need some extra logic to eliminate 1900, 1800, 1700 and 2100, 2200, 2300 and so on
.
Well, sure. Since division or mod by powers of 2 (in this case, 4), is just a bit check.
boolean isLeapYear( int year ) {
return (( year & 3 ) == 0 ); // if the bottom two bits are 0, then the int is divisible by 4
}
Note this isn't perfect, as some centuries aren't leap years, but it seems that's not relevant to your question (as you now state).
If a year is a century year, meaning divisible by 100, then it needs to be divisible by 400 to be called as a leap year.
If a year is not a century year, then it needs to be divisible by 4 to be called as a leap year.
Below Code uses binary search to check if a number is divisible by another number or not(since /
is not allowed, I am not sure if you could use %
though).
public static boolean isLeapYear(int year){
return isDivisible(1,year,100,year) ? isDivisible(1,year,400,year) : isDivisible(1,year,4,year);
}
private static boolean isDivisible(int low,int high,int divisor,int dividend){
int mid = 0;
while(low <= high){
mid = low + ((high - low) >> 1);
int result = divisor * mid;
if(result == dividend) return true;
else if(result > dividend) high = mid - 1;
else low = mid + 1;
}
return false;
}
Yes, you can do it without using any arithmetic operations. Use a Map which maps from year to a boolean - whether the year is a leap year or no.
Year.isLeap(someYear)
You should be more specific with your requirements, this is a site for programmers :)