Pages Numbering With Ink

Description


You work in a company that prints and publishes books. You are responsible for designing the page numbering mechanism in the printer. You know how many digits a printer can print with the leftover ink. Now you want to write a function to determine what the last page of the book is that you can number given the current page and numberOfDigits left. A page is considered numbered if it has the full number printed on it (e.g. if we are working with page 102 but have ink only for two digits then this page will not be considered numbered).

It’s guaranteed that you can number the current page, and that you can’t number the last one in the book.

Example

  • For current = 1 and numberOfDigits = 5, the output should be pagesNumberingWithInk(current, numberOfDigits) = 5.

    The following numbers will be printed: 1, 2, 3, 4, 5.

  • For current = 21 and numberOfDigits = 5, the output should be pagesNumberingWithInk(current, numberOfDigits) = 22.

    The following numbers will be printed: 21, 22.

  • For current = 8 and numberOfDigits = 4, the output should be pagesNumberingWithInk(current, numberOfDigits) = 10.

    The following numbers will be printed: 8, 9, 10.

Input/Output

  • [execution time limit] 4 seconds (js)

  • [input] integer current

    A positive integer, the number on the current page which is not yet printed.

    Guaranteed constraints:
    1 ≤ current ≤ 1000.

  • [input] integer numberOfDigits

    A positive integer, the number of digits which your printer can print.

    Guaranteed numberOfDigits:
    1 ≤ current ≤ 1000.

  • [output] integer

    • The last printed page number.

[JavaScript (ES6)] Syntax Tips

1
2
3
4
5
6
// Prints help message to the console
// Returns a string
function helloWorld(name) {
console.log("This prints to the console when you Run Tests");
return "Hello, " + name;
}

Solution


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
function pagesNumberingWithInk(current, numberOfDigits) {

  var n;
  while (numberOfDigits > 0) {
    if (current >= 1000) {
      n = Math.floor(numberOfDigits / 4);
      numberOfDigits = 0;
      current += n;
    } else if (current >= 100) {
      n = Math.min(1000 - current, Math.floor(numberOfDigits / 3))
      current += n;
      numberOfDigits -= n * 3;
      if (numberOfDigits < 4)
        numberOfDigits = 0
    } else if (current >= 10) {
      n = Math.min(100 - current, Math.floor(numberOfDigits / 2))
      current += n;
      numberOfDigits -= n * 2;
      if (numberOfDigits < 3)
        numberOfDigits = 0;
    } else {
      n = Math.min(10 - current, numberOfDigits)
      current += n;
      numberOfDigits -= n;
    }
  }
  return current - 1;
}