Loading

LeetCode problem#190

Reverse Bits

Solved in 2 languagesJavaRust

Solve it on LeetCode(opens in a new tab)

Solution

18 lines
1public class Solution {
2    // you need treat n as an unsigned value
3    public int reverseBits(int n) {
4        int shiftCount = 31;
5        int reversed = 0b0;
6
7        while (shiftCount >= 0) {
8            int digit = n & 1;
9            n = n >> 1;
10            if (digit == 0b1) {
11                reversed = reversed | (digit << shiftCount);
12            }
13            shiftCount--;
14        }
15
16        return reversed;
17    }
18}
1impl Solution {
2    pub fn reverse_bits(x: u32) -> u32 {
3        let mut shiftCount: i32 = 31;
4        let mut reversed: u32 = 0;
5        let mut n = x;
6
7        while (shiftCount >= 0) {
8            let digit = n & 1;
9            if (digit == 1) {
10                reversed |= (digit << shiftCount);
11            }
12
13            n = n >> 1;
14            shiftCount -= 1;
15        }
16
17        return reversed;
18    }
19}

Want a walkthrough of this Java solution?

Get a step-by-step explanation of the idea behind the code.

All problems

Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.