Leetcode / 190. Reverse Bits
Pick a programming language:
Here is the source code for the solution to this problem.
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int shiftCount = 31;
int reversed = 0b0;
while (shiftCount >= 0) {
int digit = n & 1;
n = n >> 1;
if (digit == 0b1) {
reversed = reversed | (digit << shiftCount);
}
shiftCount--;
}
return reversed;
}
}
impl Solution {
pub fn reverse_bits(x: u32) -> u32 {
let mut shiftCount: i32 = 31;
let mut reversed: u32 = 0;
let mut n = x;
while (shiftCount >= 0) {
let digit = n & 1;
if (digit == 1) {
reversed |= (digit << shiftCount);
}
n = n >> 1;
shiftCount -= 1;
}
return reversed;
}
}
Gostou da aula? 😆👍
Apoie nosso trabalho com uma doação: