NO_36_Double-base palindromes

来源:互联网 发布:sql字符串截断怎么改 编辑:程序博客网 时间:2024/05/16 04:59

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.)

代码:

import timet=time.time()def is2bitpalindromes(n):    n_str=str(bin(n))[2:]    return n_str[::-1]==n_strfinalnumlist=set()maxnum=1000000continueflag=Truefor x in range(1000):    x_str=str(x)    tempnum1=int(x_str+x_str[::-1])    if is2bitpalindromes(tempnum1):        finalnumlist.add(tempnum1)    for  tempx in xrange(0,10):        if not continueflag:            break        tempnum2=int(x_str+str(tempx)+x_str[::-1])        if tempnum2>maxnum:            continueflag=False            break        if   is2bitpalindromes(tempnum2):            finalnumlist.add(tempnum2)for x in xrange(10):    if is2bitpalindromes(x):        finalnumlist.add(x)print sorted(list(finalnumlist))print sum(finalnumlist)print time.time()-t
运行结果为:
[0, 1, 3, 5, 7, 9, 33, 99, 313, 585, 717, 7447, 9009, 15351, 32223, 39993, 53235, 53835, 73737, 585585]
872187
0.00600004196167

起初的时候有几种特殊情况我没有考虑到:
像0,1,3,5,这种个位数的

2.像9009这种数的

0 0
原创粉丝点击