2015年10月11日日曜日

151011(2)

Ruby


Number of times 1 is used in writing out all the numbers 1 through n(1)

「非公認 Googleの入社試験」に載っている次の問題を解いてみた。

Consider a function which, for a given whole number n, returns the number of ones required when writing out all numbers between 0 and n. For example, f(13)=6. Notice that f(1)=1. What is the next largest n such that f(n)=n?
(http://mathworld.wolfram.com/news/2004-10-13/google/)

i = 0
cnt = 0
num = 0
while num < 2
  i += 1
  cnt += i.to_s.count("1")
  num += 1 if i == cnt
end
p i

出力結果
199981

0 件のコメント:

コメントを投稿

注: コメントを投稿できるのは、このブログのメンバーだけです。