Why does this solution work for C# but not Java?


  • 0
    M

    C# code:

    public class Solution {
        public uint reverseBits(uint n) {
            uint getBitMask = 1;
            uint setBitMask = 1;
            setBitMask = setBitMask << 31;
            uint reversedBits = 0;
            for (int i = 0; i < 32; i ++)
            {
                if ( (n & getBitMask) > 0)
                {
                    reversedBits = reversedBits | setBitMask;
                }
                getBitMask = getBitMask << 1;
                setBitMask = setBitMask >> 1;
            }
            return reversedBits;
        }
    }
    

    Java code:

    public class Solution {
        // you need treat n as an unsigned value
        public int reverseBits(int n) {
            int getBitMask = 1;
            int setBitMask = 1 << 31;
            int reversedBits = 0;
            for (int i = 0; i < 32; i ++)
            {
                if ( (n & getBitMask) > 0)
                {
                    reversedBits = reversedBits | setBitMask;
                }
                getBitMask = getBitMask << 1;
                setBitMask = setBitMask >>> 1;
            }
            return reversedBits;
        }
    }

Log in to reply
 

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