Posts Reverse Bits (InterviewBit)
Post
Cancel

Reverse Bits (InterviewBit)

PROBLEM DESCRIPTION

Reverse the bits of an 32 bit unsigned integer A.

SOLUTION

APPROACH 1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Solution {

    public long reverse(long a) {

        long res = 0;

        for(int i=0; i<32; i++){

            if( (a&1) != 0){
                res = res | (1L<<(32-i-1));
                // res = res | (1 << (32 - i - 1)) will NOT work
                // because this will be treated as int and it will lose values beyond 2^32
            }

            a = (a>>1);

        }

        return res;

    }

}
This post is licensed under CC BY 4.0 by the author.