Solution using Stack gives me a wrong error :(


  • 0
    P

    Can anyone explain why my solution using stack gives me a wrong error? The test case I failed was:

    Input: None
    Output:
    32 (00000000000000000000000000100000)
    Expected:
    4294967295 (11111111111111111111111111111111)

       public class Solution {
        // you need treat n as an unsigned value
        public int reverseBits(int n) {        
            Stack<Integer> bit = new Stack<Integer>(); 
            for(int i=0; i<32; i++){ 
                if((n & 1)>0) {
                    bit.push(1);
                }
                else {
                    bit.push(0);
                }
                n>>>=1; 
            }
            int shifted = 0;
            int reverse_n=0;
            while(!bit.isEmpty()) {
                if(bit.pop()==0) {
                    shifted++; 
                }
                else {
                    reverse_n+=(1<<shifted); 
                }
                
            }
            return reverse_n; 
        }
    }
    

Log in to reply
 

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