我要寻找一个灵活的功能反转的一个数字的二进制重新presentation数字。
I am looking for a slick function that reverses the digits of the binary representation of a number.
如果 F
是这样的功能我会
INT(逆转(S),2)== F(INT(S,2))
只要s是零和的从1开始的字符串
int(reversed(s),2) == f(int(s,2))
whenever s is a string of zeros and ones starting with 1.
现在,我使用拉姆达X:INT(''联接(逆转(斌(X)[2:])),2)
这是确定尽可能简明而言,但似乎这样做的pretty的迂回的方式。
which is ok as far as conciseness is concerned, but it seems like a pretty roundabout way of doing this.
我在想,如果有一个更好的(也许更快)的方式与按位运算符,什么不是。
I was wondering if there was a nicer (perhaps faster) way with bitwise operators and what not.
如何
int('{0:b}'.format(n)[::-1], 2)
或
int(bin(n)[:1:-1], 2)
第二种方法似乎是两个的速度更快,但两者都比当前的方法要快得多:
The second method seems to be the faster of the two, however both are much faster than your current method:
import timeit
print timeit.timeit("int('{0:b}'.format(n)[::-1], 2)", 'n = 123456')
print timeit.timeit("int(bin(n)[:1:-1], 2)", 'n = 123456')
print timeit.timeit("int(''.join(reversed(bin(n)[2:])),2)", 'n = 123456')
1.13251614571
0.710681915283
2.23476600647