[Java] 190. Reverse binary bits---operator & and | can't be used randomly! ! !

Reverse the binary bits of a given 32-bit unsigned integer.

prompt:

Please note that in some languages ​​(such as Java), there is no unsigned integer type. In this case, both input and output will be designated as signed integer types, and should not affect your implementation, because the internal binary representation is the same regardless of whether the integer is signed or unsigned.
In Java, the compiler uses two's complement notation to represent signed integers. Therefore, in Example 2 above, the input represents a signed integer -3, and the output represents a signed integer -1073741825.

Advanced:
If you call this function multiple times, how will you optimize your algorithm?

Example 1:

Input: 00000010100101000001111010011100
Output: 00111001011110000010100101000000
Explanation: The input binary string 00000010100101000001111010011100 represents an unsigned integer 43261596,
so it returns 964176192, and its binary representation is 00111001011110000010100101000000.
Example 2:

Input: 11111111111111111111111111111101
Output: 10111111111111111111111111111111
Explanation: The input binary string 11111111111111111111111111111101 represents an unsigned integer 4294967293,
so it returns 3221225471 whose binary representation is 10111111111111111111111111111111.
Example 1:

Input: n = 00000010100101000001111010011100
Output: 964176192 (00111001011110000010100101000000)
Explanation: The input binary string 00000010100101000001111010011100 represents an unsigned integer 43261596,
so it returns 964176192, and its binary representation is 00111001011110000010100101000000.
Example 2:

Input: n = 11111111111111111111111111111101
Output: 3221225471 (10111111111111111111111111111111)
Explanation: The input binary string 11111111111111111111111111111101 represents an unsigned integer 4294967293,
so it returns 3221225471 whose binary representation is 10111111111111111111111111111111.

prompt:

The input is a binary string of length 32

代码1public static int reverseBits(int n) {
    
    
    	  int sum=0;
		  for(int i=0;i<32;i++) {
    
    
			  sum+=((n>>i)&1)<<(31-i);
		  }
    	  return sum; 
 }
代码2public static int reverseBits(int n) {
    
    
    	  int sum=0;
		  for(int i=0;i<32;i++) {
    
    
			  sum+=((n>>i)|0)<<(31-i);
			  
		  }
    	  return sum; 
}

The code 2 case has problems, so if you see it, you might as well try it! ! !

Guess you like

Origin blog.csdn.net/qq_44461217/article/details/115306267