Java Solution without Explicit Bits Manipulation


  • 0
    C

    Below is my code, which took 296ms for testing. I was stuck on finding easy ways to handle unsigned integer in Java. After several attempt, I decided to use long type to restore unsigned integer. It looks the most straightforward way to resolve this problem. Also, my method does not involve any explicit bits manipulation, which seems not so "professional" to some degree. But I still want to post here in case someone does not like bits operations just like me.

    public class Solution {
        // you need treat n as an unsigned value
        public int reverseBits(int n) {
            String str = Integer.toBinaryString(n);
            
            // expand to 32 bits
            int length = str.length();
            for (int i = 0; i < 32 - length; i++) {
                str = "0" + str;
            }
            
            // convert to unsigned int
            long result = 0;
            char[] arr = str.toCharArray();
            for (int i = 0; i < arr.length; i++) {
                result += Integer.parseInt(arr[i] + "") * Math.pow(2, i);
            }
            
            return (int)result;
        }
    }

Log in to reply
 

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