Notice
Recent Posts
Recent Comments
Link
코드로 우주평화
How many pages in a book? 본문
반응형
Description:
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.
Here's the opposite kata, which is more complex (Paginating a huge book)
Solution:
1. Get as many numbers as the summary.
2. Convert the numbers into a string.
3. If the length of the string matches the summary, the last number is returned.
def amount_of_pages(summary):
a = ''
for i in range(1, summary+1):
a += str(i)
if len(a) == summary:
return i
>>> Time: 4235ms
Best Practices:
def amount_of_pages(summary):
# 1-9: 9 = 9 * 1 * 10**0
# 10-99: 180 = 9 * 2 * 10**1
# 100-999: 2700 = 9 * 3 * 10**2
# 1000-9999: 36000 = 9 * 4 * 10**3
# 10000-99999: 450000 = 9 * 5 * 10**4
res = 0
for x in range(1, 6):
y = 9 * x * 10**(x-1)
if summary <= y:
return res + summary//x
res += y//x
summary -= y
>>> Time: 476ms
반응형
'나는 이렇게 학습한다 > Algorithm & SQL' 카테고리의 다른 글
Reverse words (0) | 2022.03.28 |
---|---|
Invert values (0) | 2022.03.27 |
Is n divisible by x and y? (0) | 2022.03.25 |
Find the divisors! (0) | 2022.03.24 |
Sum of Digits / Digital Root (0) | 2022.03.23 |