JAVA solution require no extra space runs 2ms


  • 0
    H
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
        for (int i = 0; i < 16; i++) {
            
            // two symmetric bits for comparison
            int j = 31 - i;
            
            // two digits are different, swap them
            if (((n >> i ^ n >> j) & 1) == 1) {
                n = n ^ 1 << i;
                n = n ^ 1 << j;
            }
        }
        
        return n;
    }

  • 0
    L

    Strictly, this is not "no extra space", because you use another 2 int32 variables i and j, and temporary values like n>>i is also stored on stack. No extra space doesn't make sense in this problem.


  • 0
    H

    I guess we never count the looping variables as space. You can consider them store on CPU register


  • 0
    D

    Also if using another variable for storing the result will still stored in CPU registers. So also that solution will be "no extra space" using this argument.


Log in to reply
 

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