One line Accepted Java solution 2ms, does it make sense?


  • 0
    H
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
         return Integer.reverse(n);
    }

  • 0
    H

    Use String to solve:

        public int reverseBits(int n) {
            StringBuilder sb= new StringBuilder();
            for(int i=0; i<32-Integer.toBinaryString(n).length(); i++) sb.append('0');
            sb.append(Integer.toBinaryString(n));
            return Integer.parseUnsignedInt(sb.reverse().toString(), 2);
        }
    

Log in to reply
 

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