Juni_Dev_log

(200131_TIL) 'Leap' 본문

CodingTest/Exercism

(200131_TIL) 'Leap'

Juni_K 2021. 1. 31. 14:52

▶ Leap

Leap : 윤년 계산하기

(Problem)

Introduction

Given a year, report if it is a leap year.

The tricky thing here is that a leap year in the Gregorian calendar occurs:

 

on every year that is evenly divisible by 4
except every year that is evenly divisible by 100
unless the year is also evenly divisible by 400

 

For example, 1997 is not a leap year, but 1996 is. 1900 is not a leap year, but 2000 is.

 

윤년을 계산해보는 코드를 작성해보자.

 

- 주어진 년도를 4로 나눌 수 있으면 true / 못 나누면 false.

- 주어진 년도를 100으로 나눌 수 없어야 true / 나눌 수 있으면 false.

- 주어진 년도를 400으로 나눌 있으면 true / 못 나누면 false.

 

(정리)

- 2015 : 4 / 100 / 400 모두 x => false

- 1970 : 2 (o) / 4 (x) => false

- 1996 : 4 (o) / 100,400 (x) => true

- 1960 : 4, 5 (o) => true

- 2100 : 100 (o) / 400(x) => false

- 1900 : 100 (o) / 3 (x) => false

- 2000 : 400 (o) => true

- 2400 : 400 (o) => true

- 1800 : 200 (o) / 400 (x) => false 

 

(true 의 전제조건)

① 일단 무조건 4로 나눌 수 있어야함. 

② 100으로 나누어지면, 400으로도 나누어져야함. (4/100/400 모두 나누어짐)

③ 100으로 못나누면, 아무런 상관없음.

 

(Solution)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
export const isLeap = (year) => {
    // 기본은 false
    let check = new Boolean();
 
    // 4로 나누어지는 경우
    if (year % 4 == 0){
        // 100으로 나누어지는 경우
        if (year % 100 == 0){
            // 400으로 나누어지는 경우
            if (year % 400 == 0){
                check = true;
            }
            // 400으로 못 나눈 경우
            else{
                check = false;
            }
        }
        // 100으로 못 나눈 경우
        else{
            check = true;
        }
    }
    // 4로 못 나눈 경우
    else{
        check = false;
    }
    return check;
};
 
cs

 

- 기본을 new Boolean() 을 통해서 불린형 값을 생성한다.

- 조건문을 통해서 check 를 true로 바꾸는 조건을 선별한다.

- 4로 무조건 나눌 수 있어야하고, 100은 나눌 수 있는 것에 상관없으며, 400으로 나눌 수 있어야한다.

- if / else 구문을 모두 끝내면 check 값을 return 으로 반환한다.

 

이를 조금더 간결화 시키면,

 

1
2
3
4
5
6
7
8
9
10
export const isLeap = (year) => {
    if (year % 400 === 0 ){
        return true;
    }else if(year % 4 === 0 && year & 100 !== 0){
        return true;
    }else{
        return false;
    }
};
 
cs

&& 를 사용해서. 해당 코드처럼 작성할 수 있다.

 

 

'CodingTest > Exercism' 카테고리의 다른 글

(200201_TIL) 'Collatz Conjecture'  (0) 2021.02.01
(200201_TIL) 'Reverse String'  (0) 2021.02.01
(200130_TIL) 'Matrix'  (0) 2021.01.30
(200128_TIL) 'Bank Account'  (0) 2021.01.28
(200127_TIL) 'Pangram'  (0) 2021.01.27
Comments