Problem Description:
Reverse bits of a given the unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 ( Represented in binary as00111001011110000010100101000000).
Followup:
If This function is called many times, what would you optimize it?
Related problem: Reverse Integer
C + + code implementation:
<span style= "Font-size:12px;color: #000000;" >class Solution {public: uint32_t reversebits (uint32_t N) { uint32_t result = 0;//Represents the result of the computed int temp = 0; The count is judged whether it has been moved 32 times, because most of the numbers on the left side of N are 0, so it is not necessary to loop 24-bit while (n! = 0) {result = (Result << 1) | (N & 1);//The result of each previous loop calculation is shifted one bit to the left, plus the number of digits taken from N (n & 1) n >>= 1; + + temp;} if (Temp < +) {result <<= (32-temp);} return result;} ; </span>
Java implementation: Failed to run on the system, I do not know how to handle the problem of unsigned int
public class Reverse_bits {//need treat N as an unsigned valuepublic long reversebits (long N) {Long result = 0;//represents the meter calculated result int temp = 0;//int Int_size = integer.size;//int type size while ((n! = 0) && (temp<=int_size)) {result = (Resul T << 1) | (N & 1); n >>= 1;++temp;} if (Temp < int_size) {result <<= (int_size-temp);} return result;} public static void Main (string[] args) {reverse_bits reverse_bits = new Reverse_bits (); System.out.println (Reverse_bits.reversebits (2147483648L));}}
The numbers written directly in the Java code are of type int, meaning that the number ranges from -2^31 to 2^31-1, regardless of the type assigned to the number.
When the direct assignment argument is 2147483648, the literal ... of type int is an out of range error, add L to the array, or use Long.phraselong () to resolve the problem
Leetcode-190 Reverse Bits