Skip to content

Instantly share code, notes, and snippets.

@nabeen
Created November 18, 2016 10:55
Show Gist options
  • Save nabeen/52a24eae8e64efdb14dab7d9e97159bb to your computer and use it in GitHub Desktop.
Save nabeen/52a24eae8e64efdb14dab7d9e97159bb to your computer and use it in GitHub Desktop.
数学パズルQ1
# 10進数、2進数、8進数で回文の最小値
# ただし、10進数で10以上の数とする
require 'benchmark'
# 回文チェック関数
def check(num, target)
str = num.to_s(target) # targetに指定した進数の文字列に変換
if str == str.reverse # 逆順と等しいか
return true
else
return false
end
end
# 計測時間をmsにフォーマット
def format_time(time, wait = 1000)
return time * wait
end
# 僕の書いたプログラム
num = 10
puts "start num : #{num}"
time = Benchmark.realtime do
while true
if check(num, 10) && check(num, 8) && check(num, 2)
puts "ans : #{num}"
break
end
num += 1
end
end
puts "time #{format_time(time)}ms"
puts "-------------------------"
# 模範解答
num = 11
puts "start num : #{num}"
time = Benchmark.realtime do
while true
if check(num, 10) && check(num, 8) && check(num, 2)
puts "ans : #{num}"
break
end
num += 2 # 2進で偶数の場合は最右端が0なのであり得ない
end
end
puts "time #{format_time(time)}ms"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment