油滑办法扭转了一些在Python中(二进制)的数字? [英] Slick way to reverse the (binary) digits of a number in Python?

查看:159
本文介绍了油滑办法扭转了一些在Python中(二进制)的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要寻找一个灵活的功能反转的一个数字的二进制重新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

这篇关于油滑办法扭转了一些在Python中(二进制)的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆