Very simple solution using XOR and swapping bits


  • 0
    M

    The idea is keep swapping the first and the last bit of the integer and thus reverse the bits, much like reversing a string

    Solution reference here

    public class Solution {
        // you need treat n as an unsigned value
        public int reverseBits(int n) {
            int total = 32;
            for (int i = 0; i < total / 2; i++) {
                n = swapBits(n, i, total - i - 1);
            }
            return n;
        }
    
        private int swapBits(int n, int i, int j) {
            int lo = (n >> i) & 1;
            int hi = (n >> j) & 1;
            if((lo ^ hi) == 1) { //both bits are different so need to swap
                n ^= ((1 << i) | (1 << j));
            }
            return n;
        }
    }
    

Log in to reply
 

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