Wednesday, May 9, 2018

[2018-Interview] Reverse Bits

Original question: https://leetcode.com/problems/reverse-bits/description/

My answer:


public class Solution {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
        int result = 0;
        
        for (int currentBitIndex = 0; currentBitIndex < 32; currentBitIndex ++) {
            int numberAtCurrentBitIndex = n & 1; 
            n = n >>> 1;
            int numberAtCorrespondingBitIndex = numberAtCurrentBitIndex << (31 - currentBitIndex);
            result += numberAtCorrespondingBitIndex;
        }
        return result;
    }
}

No comments:

Post a Comment