Algorithm/백준

Backjoon(백준) 2753 -윤년(Java)

GrapeMilk 2020. 2. 3. 17:57

문제

연도가 주어졌을 때, 윤년이면 1, 아니면 0을 출력하는 프로그램을 작성하시오.

윤년은 연도가 4의 배수이면서, 100의 배수가 아닐 때 또는 400의 배수일 때 이다.

예를들어, 2012년은 4의 배수라서 윤년이지만, 1900년은 4의 배수이지만, 100의 배수이기 때문에 윤년이 아니다.

하지만, 2000년은 400의 배수이기 때문에 윤년이다.

입력

첫째 줄에 연도가 주어진다. 연도는 1보다 크거나 같고, 4000보다 작거나 같은 자연수이다.

출력

첫째 줄에 윤년이면 1, 아니면 0을 출력한다.

 

 

 

-My code

import java.io.IOException;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		
		
		
		Scanner id = new Scanner(System.in);
		
		int year;
		year= id.nextInt();
		
		if (year%4 == 0)
			if (year%100 != 0 || year%400 == 0)
				System.out.println(1);
		else
			System.out.println(0);
				
		

	}

}

 

 

-Better Code

import java.io.IOException;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		
		
		
		Scanner id = new Scanner(System.in);
		
		int year;
		year= id.nextInt();
		
        
		if (year%4 == 0 && (year%100 != 0 || year%400 == 0))
			System.out.println("1");
		else
			System.out.println("0");
				
		

	}

}

 

-problem of my code

 

1. 출력되는 조건 판단할 때 if문을 2개 사용 

 -> if문 한개와 괄호 및 논리연산자를 이용하면 한 줄 표현이 가능함.

 

2. 출력되는 조건 판단할 때, else문을 빼먹음

 -> else문이 없는 경우에 25같이 4의 배수이면서 100의 배수 및 400의 배수이지 판단할 수 없는 숫자는 아무 처리도 하지 않는 상황 발생 

 

-Necessary contents

 

1. Logical operator ||(or), &&(and)

 

2. Use "==" when you write a condition in conditional sentence

 

-Solving process

 

Apply to conditional sentence as it is in the question 문제에 주어진 그대로 조건문에 대입함 (4의 배수이면서 ~)