leetcode------Reverse Bits

标题: Reverse Bits
通过率: 27.6%
难度: 简单

Reverse bits of a given 32 bits unsigned integer.

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

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

Related problem: Reverse Integer

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

这个题还是思路还是比较明确的。需要注意的就是补位的问题,给的数据不一定都是32位,所以要补位,本题我用的python,

直接代码:

 1 class Solution:

 2     # @param n, an integer

 3     # @return an integer

 4     def reverseBits(self, n):

 5         tmp=bin(n)

 6         tmp=tmp[2:]

 7         if len(tmp)!=32:

 8             for a in range(32-len(tmp)):

 9                 tmp='0'+tmp

10         tmp=tmp[::-1]

11         return int(tmp,2)

 

你可能感兴趣的:(LeetCode)