Very simple non-iterate solution


  • 7
    J
    class Solution:
        # @param n, an integer
        # @return an integer
        def reverseBits(self, n):
            n = ((n & 0x55555555) << 1) | ((n & 0xAAAAAAAA) >> 1)
            n = ((n & 0x33333333) << 2) | ((n & 0xCCCCCCCC) >> 2)
            n = ((n & 0x0F0F0F0F) << 4) | ((n & 0xF0F0F0F0) >> 4)
            n = ((n & 0x00FF00FF) << 8) | ((n & 0xFF00FF00) >> 8)
            n = ((n & 0x0000FFFF) << 16) | ((n & 0xFFFF0000) >> 16)
            return n
    

    Like merge sort, swap two bits, 4 bits, 8 bits, 16 bits and 32 bits, Then it reversed


  • 0
    N

    what's wrong with this java code?

    public int reverseBits(int b) {
        n = ((n & 0b10101010101010101010101010101010) >> 1) | ((n & 0b01010101010101010101010101010101) << 1);
        n = ((n & 0b11001100110011001100110011001100) >> 2) | ((n & 0b00110011001100110011001100110011) << 2);
        n = ((n & 0b11110000111100001111000011110000) >> 4) | ((n & 0b00001111000011110000111100001111) << 4);
        n = ((n & 0b11111111000000001111111100000000) >> 8) | ((n & 0b00000000111111110000000011111111) << 8);
        n = ((n & 0b11111111111111110000000000000000) >> 16)| ((n & 0b00000000000000001111111111111111) << 16);
        return n;
    } 
    

    doesn't work for one edge case

    Input: 65536 (00000000000000010000000000000000)

    Output: 4294934528 (11111111111111111000000000000000)

    Expected: 32768 (00000000000000001000000000000000)


  • 0
    U

    U need to use ">>>" rather than ">>".


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.