2ms Java solution


  • 1
    P
    public class Solution {
        // you need treat n as an unsigned value
        public int reverseBits(int n) {
            int rlt = 0; 
    
            for(int i = 32 ; i > 0 ; i--){
                rlt += (((n<<(i-1))>>>31)<<(i-1));
            }
    
            return rlt;
        }
    }

  • 0
    W

    public class Solution {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
    int temp = 0;
    int result = 0;
    int array[] = new int[32];
    int i = 0;
    for ( i = 0; i < 32; i++){
    temp = n % 2;
    n = n / 2;
    temp = (temp) <<(31 - i);
    result = result + temp;
    }

        return result;
    }
    

    }
    anyone can help me why this not correct


  • 0
    P

    The problem is at "n = n / 2;". It does not treat n as an unsigned value. It works to use "n = n >>> 1;".


  • 0
    P

    @wei130
    Your code can be accepted if modified as below:

    public class Solution {
        // you need treat n as an unsigned value
        public int reverseBits(int n) {
            int temp = 0;
            int result = 0;
            int array[] = new int[32];
            int i = 0;
    
            for ( i = 0; i < 32; i++) {
                temp = n % 2;
                n = n >>> 1;
                temp = (temp) << (31 - i);
                result = result + temp;
            }
    
            return result;
        }
    }

  • 0
    L

    Very smart solution.


  • 0
    P

    Thank you. :)


  • 0
    K

    this line is useless:
    int array[] = new int[32];


Log in to reply
 

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