Java solution, in-place using XOR


  • 0
    D

    This solution swaps bits from the two ends of the number in pairs.
    It uses XOR to swap the values.

    public class Solution {
        // you need treat n as an unsigned value
        public int reverseBits(int n) {
            
            for (int i = 0; i < 16; i ++) {
                int leftDigit = (n >>> (31 - i)) & 1;
                int rightDigit = (n >>> i) & 1
                n = n ^ (leftDigit << i); // XOR with new value
                n = n ^ (rightDigit << i); // XOR with its original value to leave the new value behind
                n = n ^ (rightDigit << (31 - i)); // same idea here, but for the one on the left
                n = n ^ (leftDigit << (31 - i));
            }
            
            return n;
            
        }
    }
    

Log in to reply
 

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