您的位置:首页 > 其它

190. Reverse Bits

2016-07-19 15:44 351 查看

190. Reverse Bits

Leetcode link for this question

Discription:

Reverse bits of a given 32 bits unsigned integer.

For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).

Follow up:

If this function is called many times, how would you optimize it?

Analyze:

Code 1:

class Solution(object):
def reverseBits(self, n):
"""
:type n: int
:rtype: int
"""
bi=str(bin(n))[2:]
bi='0'*(32-len(bi))+bi
s=0
wei=1
for i in bi:
s=int(i)*wei+s
wei*=2
return s


Submission Result:

Status: Accepted

Runtime: 68 ms

Ranking: beats 31.14%

Code 2:

class Solution(object):
def reverseBits(self, n):
"""
:type n: int
:rtype: int
"""
for i in range(16):
j=32-i-1
if i>j:
break
bi=(n>>i)&1
bj=(n>>j)&1
if bi^bj:
n=n^(1<<i)^(1<<j)
return n


Submission Result:

Status: Accepted

Runtime: 72 ms

Ranking: beats 21.27%
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: