HR - Drawing Book
문제
A teacher asks the class to open their books to a page number. A student can either start turning pages from the front of the book or from the back of the book. They always turn pages one at a time. When they open the book, page 1
is always on the right side:
When they flip page 1
, they see pages 2
and 3
. Each page except the last page will always be printed on both sides. The last page may only be printed on the front, given the length of the book. If the book is n
pages long, and a student wants to turn to page p
, what is the minimum number of pages to turn? They can start at the beginning or the end of the book.
Given n
and p
, find and print the minimum number of pages that must be turned in order to arrive at page p
예시
6
2
// 1
5
4
// 0
풀이
- 전체 페이지/2 를 목표 페이지와 비교하여 페이지 넘기기를 시작할 지점을 고른다.
- 페이지를 뒷페이지부터 넘길 때, 끝 페이지가 짝수이면서 목표 페이지가 바로 앞 페이지일 경우를 거른다.
- 페이지를 앞에서, 혹은 뒤에서 넘기기 시작하느냐에 따라 분기를 나눠
page
를2
씩 증가 혹은 감소시킨다. 그때마다 페이지를 넘기는 횟수를 기록한다. - 페이지를 넘긴 횟수를 반환한다.
코드
function pageCount(n, p) {
let page = 1;
let pageTurn = 0;
if(n/2 < p){
page = n; // right 에서부터 넘기기
if(page % 2 !== 0 && page-1 === p) return 0;
}
if(page === 1) {
while(page < p) {
page += 2;
pageTurn++;
}
} else{
if(page % 2 === 0) {
while(page >= p+1) {
page -= 2;
pageTurn++;
}
}
else {
while(page > p+1) {
page -= 2;
pageTurn++;
}
}
}
return pageTurn;
}
Author And Source
이 문제에 관하여(HR - Drawing Book), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@goody/HR-Drawing-Book저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)