Concise Java Solution


  • 3
    S

    The key here is to use ">>>" instead of ">>"

    1000 >> 1 becomes 1100

    1000 >>>1 becomes 0100

    public class Solution {
        // you need treat n as an unsigned value
        public int reverseBits(int n) {
            int m = 0;
            for(int i = 0;i < 32;i++)
                if((n & (0x00000001 << i)) != 0) m |= (0x80000000 >>> i);
            return m;
        }
    }

Log in to reply
 

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