読者です 読者をやめる 読者になる 読者になる

mu chance or much chance ?

日々の戯れ言

Project Euler 36

Project Euler

Problem36を解きました.

  • Double-base palindromes

The decimal number, 585 = 10010010012 (binary), is palindromic in both bases.

Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.

(Please note that the palindromic number, in either base, may not include leading zeros.)

https://projecteuler.net/problem=36

問題は「100万未満の自然数で10進数・2進数でも回文数になる数の総和を求めよ.ただし,先頭に0が含む数を回文数とみなしてはいけない.」.

sum = 0
i = 1
while i < 1000000 do
	if i.to_s == i.to_s.reverse && i.to_s(2) == i.to_s(2).reverse then
		sum += i
	end
	i += 1
end

p sum

数値を文字列に直せば,reverseで回文かどうか判断できます.