zoukankan      html  css  js  c++  java
  • 180415_判断闰年的思路及三种 java 实现

    世纪年:能整除 100 的年份

    普通年:不能整除 100 的年份

    闰年:一年有 366 天,二月有 29 天

    平年:一年有 365 天,二月有 28 天

    对于世纪年:能整除 400 为闰年,否则为平年

    对于普通年:能整除 4 为闰年,否则为平年

    以下是代码实现:

    1、普通两层 if 嵌套语句:

    最为接近伪代码的逻辑,简单易懂

     1 if (year % 100 == 0) {
     2     if (year % 400 == 0) {
     3         System.out.println("世纪年 闰年");
     4     } else {
     5         System.out.println("世纪年 平年");
     6     }
     7 } else{
     8     if (year % 4 == 0) {
     9         System.out.println("普通年 闰年");
    10     } else {
    11         System.out.println("普通年 平年");
    12     }
    13 }

    2、IDEA 提示修改后的 if 嵌套 以及 if ... else ... if 语句:

    少用了一层嵌套,在不必要嵌套的地方去除嵌套,采用 else ... if 多分支语句

     1 if (year % 100 == 0) {
     2     if (year % 400 == 0) {
     3         System.out.println("世纪年 闰年");
     4     } else {
     5         System.out.println("世纪年 平年");
     6     }
     7 } else if (year % 4 == 0) {
     8     System.out.println("普通年 闰年");
     9 } else {
    10     System.out.println("普通年 平年");
    11 }

    3、使用三目判断运算符精简代码量后的语句:

    单条版

    1 System.out.println(year % 100 == 0 ? (year % 400 == 0 ? "世纪年 闰年" : "世纪年 平年") : (year % 4 == 0 ? "世纪年 闰年" : "世纪年 平年"));

    缩进版

    1 System.out.println(
    2         year % 100 == 0 ?
    3                 (year % 400 == 0 ? "世纪年 闰年" : "世纪年 平年") :
    4                 (year % 4 == 0 ? "世纪年 闰年" : "世纪年 平年")
    5 );

    注明:内语句的  () 不必要,是为了方便理解而加上的

  • 相关阅读:
    (转)【web前端培训之前后端的配合(中)】继续昨日的故事
    ural(Timus) 1136. Parliament
    scau Josephus Problem
    ACMICPC Live Archive 6204 Poker End Games
    uva 10391 Compound Words
    ACMICPC Live Archive 3222 Joke with Turtles
    uva 10132 File Fragmentation
    uva 270 Lining Up
    【转】各种字符串哈希函数比较
    uva 10905 Children's Game
  • 原文地址:https://www.cnblogs.com/ram314/p/8850015.html
Copyright © 2011-2022 走看看