DEV Community

Cesar Del rio
Cesar Del rio

Posted on

#42 - How many pages in a book? - Codewars Kata (6 kyu)

Instructions

Task
Every book has n pages with page numbers 1 to n. The summary is made by adding up the number of digits of all page numbers.

Task: Given the summary, find the number of pages n the book has.

Example

If the input is summary=25, then the output must be n=17: The numbers 1 to 17 have 25 digits in total: 1234567891011121314151617.

Be aware that you'll get enormous books having up to 100.000 pages.

All inputs will be valid.


My solution:

function amountOfPages(summary){
  if(summary <= 9) return summary
  var count = 0;
  var res = 0;
  for(let i = 1; i<summary; i++){
    count+=i.toString().length
    if(count==summary) res = i
  }
  return res
}
Enter fullscreen mode Exit fullscreen mode

Explanation

First I used a conditional if the summary pages are less than 9 it means that the digits are the same as the original one

if(summary <= 9) return summary
Enter fullscreen mode Exit fullscreen mode

Then I created two variables:

  1. count where I'll store the count of the pages digits.
  2. res where I'll store the last result.
var count = 0;
var res = 0;
Enter fullscreen mode Exit fullscreen mode

I used a for loop so I could go through every page and in every iteration I add to the variable count the total digits of the page number that is being iterated. Until the variable count is equal to summary, that means that I'm located in the exact page number "i", so I set "res" as the variable "i".

At the end I just return res

for(let i = 1; i<summary; i++){
  count+=i.toString().length
  if(count==summary) res = i
}

return res
Enter fullscreen mode Exit fullscreen mode

What do you think about this solution? 👇🤔

My Github
My twitter
Solve this Kata

Discussion (0)