One of most concise solutions in Java


  • 6
    D
    public class Solution {
        // you need treat n as an unsigned value
        public int reverseBits(int n) {
            int reverse = 0;
            for (int i = 0; i < 32; ++i) {
                reverse = (reverse << 1) ^ (n & 0x1);
                n >>>= 1;
            }
            return reverse;
        }
    }
    

    Any suggestions? Thanks.


  • 1
    M

    Similar solution:

    Take shift each bit out and shift it in the other way.

     public int reverseBits(int n) {
        int y = 0;
        int digit = 0;
        int x = n;
        
        for(int i = 0 ; i < 32; i++){
             y = y << 1;
             digit = x & 1;
             y = y | digit;
             x = x >> 1;
        }
        
        return y;
    }

  • 0
    D

    your solution is actually almost the same as mine. :)


  • 0
    M

    Yeah. Always think bit-level!


  • 0
    X

    clear enough


  • 0
    H
    public int reverseBits(int n) {
        int result = 0;
        for(int i = 31; i >= 0; i--){
            result |= (n&1)<<i;
            n >>>= 1;
        }
        
        return result;
    }

Log in to reply
 

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