plz help me! I'm confused...


  • 0
    B

    I don't know why the first solution is correct but the second one is wrong.
    e.g. when input n = 1, the output of second solution is 0 and the expected answer is 2147483648 (10000000000000000000000000000000). Yet the first solution passes the test.

        public int reverseBits(int n) {
            n = ((n & 0x55555555) << 1) | ((n & 0xaaaaaaaa) >>> 1);
            n = ((n & 0x33333333) << 2) | ((n & 0xcccccccc) >>> 2);
            n = ((n & 0x0f0f0f0f) << 4) | ((n & 0xf0f0f0f0) >>> 4);
            n = ((n & 0x00ff00ff) << 8) | ((n & 0xff00ff00) >>> 8);
            n = ((n & 0x0000ffff) << 16) | ((n & 0xffff0000) >>> 16);
            return n;
        }
    
        public int reverseBits(int n) {
            int result = 0;
            for (int i = 0; i < 32; i++, n >>>= 1, result <<= 1) {
                if ((n & 1) != 0) {
                    result |= 1;    
                }
            }
            return result;
        }
    

Log in to reply
 

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