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:
老師要求全班打開書本。 學生可以從書的正面或背面開始翻頁。 他們總是一次翻一頁。 當他們打開書時,第一頁的 1 永遠在右邊。
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.
當他們翻動第 1 頁時,他們會看到第 2 頁和第 3 頁。除了最新的一頁之外的每一頁都將始終進行雙面打印。 如果這本書有 n 頁長,學生想翻到第 p 頁,那麼最少要翻多少頁? 它們可以從書的開頭或結尾開始。 給予 n 和 p,找到到達第 p 頁必須翻過的最少頁數。
Example 1:
n = 5, p = 3 book = [0, 1, 2, 3 , 4 ,5]
solution:
這裡要特別注意,題目再給予的規範內希望找到「從前面」、「從後面」翻頁到指定的數字,
所以考量以上兩個方式中,可以用最小的頁數達到目標為最後的回傳值。
Code 1: BigO(n)
'use strict'; const fs = require('fs'); process.stdin.resume(); process.stdin.setEncoding('utf-8'); let inputString = ''; let currentLine = 0; process.stdin.on('data', function(inputStdin) { inputString += inputStdin; }); process.stdin.on('end', function() { inputString = inputString.split('\n'); main(); }); function readLine() { return inputString[currentLine++]; } /* * Complete the 'pageCount' function below. * * The function is expected to return an INTEGER. * The function accepts following parameters: * 1. INTEGER n * 2. INTEGER p */ function pageCount(n, p) { // Write your code here const fromFront = Math.floor(p / 2); const fromBack = Math.floor(n / 2) - fromFront; return Math.min(fromFront, fromBack); } function main() { const ws = fs.createWriteStream(process.env.OUTPUT_PATH); const n = parseInt(readLine().trim(), 10); const p = parseInt(readLine().trim(), 10); const result = pageCount(n, p); ws.write(result + '\n'); ws.end(); }
FlowChart:
Example 1
n = 5, p = 3 book = [0, 1, 2, 3 , 4 ,5] fromFront = Math.floor(p / 2) = 1.5 => 1 fromBack = Math.floor(n / 2) - fromFront = 2 - 1 = 1 return Math.min(fromFornt, fromBack) //1