Skip to content

Instantly share code, notes, and snippets.

@pocari
Created July 8, 2014 13:09
Show Gist options
  • Save pocari/30b445060befb5e99ea0 to your computer and use it in GitHub Desktop.
Save pocari/30b445060befb5e99ea0 to your computer and use it in GitHub Desktop.
nthdigit.rb
class Solver
def initialize(first_num)
#5~のリストだと考えにくかったため、
#1~のリストに対して、それと5(ここではfirst_numとして変数化)ずれた値を求めるためのオフセット
@first_num = first_num
end
#1から始まる数字の列として考える上で、下記の様に「レンジ」という言葉を定義します
#1 2 ... 8 9 10 11 12 13 ... 98 99 100 101 102 ... 998 999
#^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^
# 10^0のレンジ 10^1のレンジ 10^2のレンジ
def solve(index)
#1~始まったリストの場合に何番目を求めることになるかを計算
n = index + @first_num - 1
#指定された位置がどのレンジに入り、そのレンジまでに何個の数字が存在していたかを計算
power, past_num = search_num_size(n)
keta = power + 1
#nth ... そのレンジの中で何番目の数値にあたるか?
if power == 0
#10^0のレンジのみ1から始まるのでその調整用
nth = (n - past_num).div(keta)
digit = 10 ** power + nth - 1
else
nth = (n - past_num - 1).div(keta)
digit = 10 ** power + nth
end
#pos ... nth番目の数字の何桁目の数字かを計算
pos = (n - past_num - 1) % keta
#p [:n_power_past, n, power, past_num]
#p [:nth, nth]
#p [:pos, pos]
#p [:digit, digit]
#p [:num, digit.to_s[pos]]
digit.to_s[pos]
end
private
#n桁(10のn)に含まれる数字の個数
def num_in_10n(n)
(10 ** (n + 1) - (10 ** n)) * (n + 1)
end
def search_num_size(n)
i = 0
index = 0
while true
num = num_in_10n(i)
index += num
#p [:info_i_n_index, i, n, index]
if n <= index
return [i, index - num]
end
i += 1
end
end
end
#検算用
$ary = (5 ... 1000000).to_a.join
#p $ary
def check(n)
$ary[n - 1]
end
solver = Solver.new(5)
readlines.each do |n|
puts solver.solve(n.to_i)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment