In this Drawing Book HackerRank Problem, 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 is always on the right side:
When they flip page , they see pages and . 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 pages long, and a student wants to turn to page , what is the minimum number of pages to turn? They can start at the beginning or the end of the book.
Given and , find and print the minimum number of pages that must be turned in order to arrive at page .
Example
Using the diagram above, if the student wants to get to page , they open the book to page , flip page and they are on the correct page. If they open the book to the last page, page , they turn page and are at the correct page. Return .
Function Description
Complete the pageCount function in the editor below.
pageCount has the following parameter(s):
- int n: the number of pages in the book
- int p: the page number to turn to
Returns
- int: the minimum number of pages to turn
Input Format
The first line contains an integer , the number of pages in the book.
The second line contains an integer, , the page to turn to.
Constraints
Drawing Book HackerRank Problem Solutions
I will Provide solution in Multiple programming languages for you. If you are not able to find the code in required language then please share in comments so that our team can help you.
Problem Solution in JavaScript
function pageCount(n, p) {
let df = Math.floor(n/2);
let dp = Math.floor(p/2);
return Math.min(dp, df-dp);
}
Drawing Book Problem Solution in Python
def pageCount(n,p):
if n%2 == 0:
n += 1
forward_turns = int(p//2)
backward_turns = int((n-p)//2)
return min(forward_turns,backward_turns)
Problem Solution in C++
int pageCount(int n, int p) {
int turns=0;
if(p<=n/2)
turns=p/2;
else
{
if(n%2==1)
turns=(n-p)/2;
else if(n%2==0)
turns=(n-p+1)/2;
}
return turns;
}
Drawing Book Problem Solution in C#
public static int pageCount(int n, int p)
{
if(n%2 == 0){
n++;
}
var pageFlipFromStart = Math.Floor((double)p/2);
var pageFlipFromEnd = Math.Floor((double)(n-p)/2);
return pageFlipFromStart < pageFlipFromEnd ? (int)pageFlipFromStart : (int)pageFlipFromEnd;
}
Problem Solution in Java
public static int pageCount(int n, int p)
{
if(n%2 == 0){
n++;
}
var pageFlipFromStart = Math.Floor((double)p/2);
var pageFlipFromEnd = Math.Floor((double)(n-p)/2);
return pageFlipFromStart < pageFlipFromEnd ? (int)pageFlipFromStart : (int)pageFlipFromEnd;
}