LeetCode-109-Reverse Binary Bits (Simple)

1. Description

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

2. Example

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.

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

Tip:
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?

3. Analysis

Reversing a binary string is essentially the same as reversing a string. You can directly use all methods of reversing a string. (Omitted: recursion, reverse loop, push and pop, etc.)
However, because of the particularity of the problem, you can use built-in classes.

The wrapper class Integer encapsulates the method of directly inverting the integer binary string and returning the inverted integer

class Method name Features
Integer static int reverse​(int i) Returns the value obtained by reversing the order of the bits in the two’s complement binary representation of the specified int value.

4. Code

public class Solution {
    
    
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
    
    
        return Integer.reverse(n);
    }
}

5. Verification

Insert picture description here

Guess you like

Origin blog.csdn.net/PursueLuo/article/details/108734133