Don't know what's wrong with my java code


  • 0
    V

    public class Solution {

    public int reverseBits(int n) {
    
        int result = 0;
        int[] m = new int[32];
        for(int i = 0; i < m.length; i++){
            m[i] = (n & 1);
            n = n >> 1;
        }
        
        for(int j = 0; j < m.length; j++){
            result = (result | m[j]);
            result = result << 1;
        }
        
        return result;
    }
    

    }

    when execute n = 1, this function return the wrong answer, 0. Can anybody help me?


  • 0
    X

    You code shift 32 times for the result, which moves the 1 in the last bit to the sign.
    Use >>> instead of >>


Log in to reply
 

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