Leetcode 190. Reverse Bits

Kostya
Mar 9, 2021

Reverse bits of a given 32 bits unsigned integer.

Since Java doesn’t have unsigned numbers, this task becomes a way more interesting. The simplest way would be to operate with bits, I’ve added a bunch of comments to the code to make it clear

public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int res = 0;
for (int i = 0; i < 32; i++) {
// shift to the left, i.e. ...001 is changed into ...010
res <<= 1;
// n&1 - keep 1 at the end of n if it ends with 1
// | if n ends with 1, then res is also ends with 1
res = res | (n & 1);
n >>= 1; // shift n to the right for 1 position
}
return res;

}
}

--

--

Kostya

Java, start-up, hiking, photos, bicycle,journey