Concise Java Solution


  • 28
    Z
     public int reverseBits(int n) {
      int result = 0;
      for (int i = 0; i < 32; ++i) {
        result = result<<1  | (n & 1);
        n >>>= 1;
      }
    return result;  }

  • 1
    E

    my code was like:

    public class Solution {
        // you need treat n as an unsigned value
        public int reverseBits(int n) {
            int result = 0;
            for(int i = 0; i < 32; i++) {
                result |= n & 0x1;
                result = result << 1;
                n >>>= 1;
            }
            return result;
        }
    }
    

    but failed, what's wrong with it?thanks.


  • 0

    The or operator is executed before the and operator


  • 0
    Z

    you should run

    result = result << 1;

    first, your code will work if switch these two lines below:

    
     result = result << 1;
     result |= n & 0x1;
     

  • 0
    W

    I think you should not shift for the last digit


Log in to reply
 

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