首页 > 解决方案 > Check Leap Year - without using division operation

问题描述

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

标签: javaalgorithmleap-year

解决方案


以下是一些不使用模函数来识别闰年的方法。

首先,让我们假设(或测试)年份在范围内1901 - 2099

  • 以二进制数表示的闰年将具有00最后两位数字。所以:

    这是闰年if year & (not 4) == 0

  • 如果您有可将实数截断为整数的函数,则此方法有效:

    x = trunc(year / 4)

    这是闰年if x * 4 == year

  • 如果您有移位(不是循环移位)运算符,我确信 Verilog 有:

    x = year >> 2

    这是闰年if (x << 2) == year

如果关于范围的假设1901 - 2099是错误的,那么您将需要一些额外的逻辑来消除1900, 1800, 1700 and 2100, 2200, 2300 and so on.


推荐阅读