What's wrong with my Java code?


  • 0
    C

    I know the other solution using bit shift. Please help me understand the problem here.

    public class Solution {
        // you need treat n as an unsigned value
        public int reverseBits(int n) {
            long sum = 0;
            int digit = 31;
            while (n > 0) {
                if ((n&1) == 1) sum += Math.pow(2, digit);
                n >>>= 1;
                digit--;
            }
            return (int)sum;
        }
    }
    

    Err Message:

    • Input: 2147483648 (10000000000000000000000000000000)
    • Output: 0 (00000000000000000000000000000000)
    • Expected: 1 (00000000000000000000000000000001)

  • 4
    Y

    Try with the condition "while(n!=0)".
    In Java, 2147483648 means - 2147483648, which is less than 0, so your bit manipulation will not work.


  • 0
    J

    In java, when you solve unsigned int problem, you should consider bit operation first.
    for += Math.pow(2, digit), you could use | (n&1)<<digit


Log in to reply
 

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