Reverse Bits
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 the called many times, how to would you optimize it?
The complexity of Shift method
Time O (1) space O (1)
Ideas
The simplest way to do this is to move the original number to the right and remove the lowest bit, assigning the new number to the lowest bit and then moving to the left.
Code
public class Solution { // you need treat n as an unsigned value public int reverseBits(int n) { int res = 0; for(int i = 0; i < 32; i++, n >>= 1){ res = res << 1 | (n & 1); } return res; }}
Piecewise phase or method complexity
Time O (1) space O (1)
Ideas
Java Standard integer.reverse () source code.
Code
public class Solution {You need treat n as a unsigned value public int reversebits (int i) {i = (I &0x55555555) << 1 | (I >>> 1) & 0x55555555; i = (I & 0x33333333) << 2 | (I >>> 2) & 0x33333333; i = (I & 0x0f0f0f0f) << 4 | (I >>> 4) & 0x0f0f0f0f; i = (i << 24) | ((I & 0xff00) << 8) | ((I >>> 8) & 0xff00) | (i >>> ); return i;}}
Subsequent follow up
Q: What is the optimization method if the method is called extensively or used to process the Bulk data?
A: This is actually the essence of the problem, the investigation of large-scale data at the most basic optimization method of the algorithm. In fact, the truth is very simple, repeated to use the things written down on the line, so we use a map to record the previous reversal of the numbers and results. A better method of optimization is to save space by dividing it into 4 segments of bytes. See this post.
CachePrivate final Map<byte, integer> cache =New Hashmap<byte, integer> ();PublicIntReversebits (int n) {byte[] bytes =Newbyte[4];for (int i =0; I <4; i++)convert int into 4 bytes bytes[i] = (BYTE) ((N >>>8*i) &0xFF);int result =0;for (int i =0; I <4; i++) {result + = Reversebyte (Bytes[i]);Reverse per byteif (I <3) Result <<=8; }return result;}PrivateIntReversebyte (Byte b) {IntegerValue = cache.Get (b);//First look up from cache if (value! = null) return value; value = 0; //reverse by bit for (int i = 0; i < 8; i++) { Value + = ((b >>> i) & 1); if (I < 7) value <<= 1;} cache.put (b, value); return value;}
Turn from: 1190000003483740
Algorithm: Reverse bits Reverse Bit collection