Accepted Java Solution with Comments


  • 0
    Z
    public class Solution {
        // you need treat n as an unsigned value
        public int reverseBits(int n) {
    		int mask = 0x80000000;   // (8)hex = (1000)bin
            int reverse = 0;
            while(n != 0){
                int bit = n & 1;    //get one bit from input
                bit *= mask;        //shift to the left end
                reverse |= bit;     //put the bit into the result
                mask >>>= 1;        //shift the mask 1-bit to the right
                n >>>= 1;           //shift input 1-bit to the right
            }
            return reverse;
        }
    }

Log in to reply
 

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