In this post, we will solve the Drawing Book Sequence HackerRank Solution. This problem (Drawing Book Sequence) is a part of the HackerRank Problem Solving series.
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:
Original Problem Link: https://www.hackerrank.com/challenges/three-month-preparation-kit-drawing-book/problem
Drawing Book Hacker Rank Solution
Problem solution in JavaScript programming:
function pageCount(n, p) { //If n is pair > add 1 to it if( n%2 == 0){ n++} const maxFlip = n/2 const flipNeeds= p/2 if ((n/2)>p){ return parseInt(flipNeeds) }else{ const reverse = maxFlip - parseInt(flipNeeds) return parseInt(reverse) } }
Problem solution in Python programming:
def pageCount(n, p): # Write your code here n = n // 2 p = p // 2 return min(n-p, p)
Problem solution in C++ programming:
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; }
Problem solution in Ruby programming:
def pageCount(n, p) limit = n / 2 n = n.even? ? n + 1 : n p = n - p if p > limit p / 2 end
Leave a Reply