티스토리 뷰
// for문 쓰지않고 while 문 사용하기
static int dayOfYear(int y, int m, int d) {
int days = d;
int year = isLeap(y);
int month = 0;
while (month < m-1) {
days += mdays[year][month];
month++;
}
return days;
}
(1)
class DayOfYearWhile_02_08 {
// 각 달의 일 수
static int[][] mdays = { { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, // 평년
{ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, // 윤년
};
// 서기 year년은 윤년인가? (윤년:1/평년:0)
static int isLeap(int year) {
return (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) ? 1 : 0;
}
// 서기 y년 m월 d일의 연내의 경과일수를 구합니다.
static int dayOfYear(int y, int m, int d) {
while (--m != 0)
d += mdays[isLeap(y)][m - 1];
return (d);
}
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
int retry; // 한 번더 ?
System.out.println("연내의 경과 일 수를 구합니다.");
do {
System.out.print("년:");
int year = stdIn.nextInt(); // 년
System.out.print("월:");
int month = stdIn.nextInt(); // 월
System.out.print("일:");
int day = stdIn.nextInt(); // 일
System.out.printf("연내 %d일째입니다.\n", dayOfYear(year, month, day));
System.out.print("한번 더 할까요? (1.예/0.아니오):");
retry = stdIn.nextInt();
} while (retry == 1);
}
}
(2)
while (m-1 != 0) {
d += mdays[isLeap(y)][m - 1];
m--;
}
(3)
- 답안코드가 훨씬 깔끔함
- for문만 써서 그런지 while문 쓰는게 조금 어려움
- while문을 저렇게 써도 될거같은데 그래도 답안코드가 더 깔끔해보임
※참조
Do it! 자료구조와 함께 배우는 알고리즘 입문
'PS > etc' 카테고리의 다른 글
chapter3-Q3) 배열에서의 검색 (0) | 2020.07.13 |
---|---|
chapter2) 그 해의 남은 일 수 구하기 (0) | 2020.07.09 |
chapter2) 소수 구하기 (0) | 2020.07.09 |
chapter2) 10진수 변환 (0) | 2020.07.08 |
chapter2) 배열 요소의 합계 구하기 (0) | 2020.07.07 |
링크
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
TAG
- 이펙티브자바 스터디
- 이펙티브자바 아이템59
- REST API
- 이펙티브자바 아이템60
- JS 딥다이브
- 김영한 http
- dreamcoding
- GCP
- 프로그래머스 SQL
- 킹수빈닷컴
- js api
- 김영한 JPA
- 백기선 스터디
- js promise
- js array
- java
- Spring Security
- 이펙티브자바
- ㅇㄷㅇㅈ
- 드림코딩
- 가상 면접 사례로 배우는 대규모 시스템 설계 기초
- BOJ
- HTTP 완벽가이드
- 프로그래머스
- 백준
- HTTP 완벽 가이드
- http
- 모던자바스크립트
- JPA 연관관계 매핑
- 패스트캠퍼스 컴퓨터공학 완주반
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 30 |
31 |
글 보관함