대칭수(palindrome)인 585는 2진수로 나타내도 10010010012가 되어 여전히 대칭수입니다.
10진법과 2진법으로 모두 대칭수인 1,000,000 이하 숫자의 합을 구하세요.
(주의: 첫번째 자리가 0이면 대칭수가 아님)
특별히 어려울 것이 없었음..
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def isPalindrome(n): | |
n_str = str(n) | |
reverse_str = n_str[::-1] | |
return n_str == reverse_str | |
result=0 | |
for n in range(0, 1000001): | |
n_2 = str(bin(n))[2:] | |
if not isPalindrome(n): | |
continue | |
if n_2[0:1] == 0: | |
continue | |
if not isPalindrome(n_2): | |
continue | |
result+=n | |
print(result) |
Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def isPalidrome(n) | |
n_str = n.to_s | |
reverse_str = n_str.reverse | |
return n_str == reverse_str | |
end | |
result=0 | |
(0..1000000).each do |n| | |
n_2 = n.to_s(2) | |
unless isPalidrome(n) | |
next | |
end | |
if n_2[0,1] == 0 | |
next | |
end | |
unless isPalidrome(n_2) | |
next | |
end | |
result+=n | |
end | |
puts "#{result}" |
Perl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use strict; | |
use warnings; | |
sub isPalidrome { | |
my ($n) = @_; | |
my $reverse_n = reverse $n; | |
return $reverse_n == $n; | |
} | |
my $result = 0; | |
foreach my $n ((0..1000000)) { | |
if (!isPalidrome($n)) { | |
next; | |
} | |
if ((substr $n, 0, 1) == 0) { | |
next; | |
} | |
my $n_2 = sprintf("%b", $n); | |
if (!isPalidrome($n_2)) { | |
next; | |
} | |
$result+=$n; | |
} | |
print "$result"; |