Will Clausen's Website

Categories
WCW

Project Euler Problem 36

Another one bites the dust! I worked with my brother David on this one, so a big thanks to him for his help.

Here’s the problem:
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.)

My Solution:

# Authors: William and David Clausen
# Date: 8/4/13
# Description: Project Euler Problem 36

# Function that solves Project Euler Problem 36.
def problem36(limit):
        total = 0
        check = 1
        while check < limit:
                strCheck = str(check)
                # Take advantage of helpful format function to change the
                # checked number into a string in base 2!
                strBase2 = format(check, 'b')

                if isPalindrome(strBase2) and isPalindrome(strCheck):
                        total += check

                check += 2

        return total

# This function determines if a given string is a palindrome. O(n).
def isPalindrome(string):
        for x in range(len(string)/2):
                if string[x] != string[-x - 1]:
                        return False

        return True
                        
if __name__ == "__main__":
        answer = problem36(1000000)
        print "Answer is: " + str(answer)

Leave a Reply

Your email address will not be published.