Topic links
https://leetcode.com/problems/reverse-bits/
Original title
Reverse bits of a given the unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represent Ed in binary as 00111001011110000010100101000000).
Follow up:
If This function is called many times, what would you optimize it?
Topic translation
Flips the bit of a given 32-bit unsigned number. For example, given an input integer 43261596 (binary represented as 00000010100101000001111010011100), return 964176192 (binary represented as 00111001011110000010100101000000).
Further: If the function is called multiple times, how do you optimize it?
Method of Thinking
Idea one
The input is converted into a 2-character string, then flipped and expanded to 32-bit, and the binary of this 32-bit is converted to an unsigned integer. Using the Python bin () function is convenient.
Code
class Solution(object): def reverseBits(self, n): """ :type n: int :rtype: int """ b = bin(n)[:1:-1] return‘0‘*(322)
Idea two
bitwise processing, the binary representation of the input n from the low to the high value of the values are taken out, reverse order to get the value after flipping. When you update res here, it is much faster to use a pure bit operation than to add it.
Code
class Solution(object): def reverseBits(self, n): """ :type n: int :rtype: int """ 0 forin xrange(32): 1 1) return res
Three Ideas
There is also a more ingenious way to look more violent. Similar to the two-point idea, each processing half of the bit exchange, the specific look at the code bar.
Code
class solution(object): def reversebits(self, n): "" : Type N:int:rtype:int "" "n = (n >> -) | (N << -); n = ((N &0xff00ff00) >>8) | (N &0x00ff00ff) <<8); n = ((N &0xf0f0f0f0) >>4) | (N &0x0f0f0f0f) <<4); n = ((N &0XCCCCCCCC) >>2) | (N &0x33333333) <<2); n = ((N &0xaaaaaaaa) >>1) | (N &0x55555555) <<1);returnN
PS: Novice Brush Leetcode, new handwritten blog, write wrong or write not clear also please help point out, thank you!
Reprint Please specify: http://blog.csdn.net/coder_orz/article/details/51705094
Reverse Bits [Easy] (Python)