-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse-bits.ts
More file actions
29 lines (27 loc) · 780 Bytes
/
Copy pathreverse-bits.ts
File metadata and controls
29 lines (27 loc) · 780 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* 190. Reverse Bits (Easy)
* Link: https://leetcode.com/problems/reverse-bits/
*
* Reverse the bits of a given 32-bit unsigned integer.
*
* Example:
* Input: n = 0b00000010100101000001111010011100
* Output: 0b00111001011110000010100101000000 (964176192)
*
* Approach:
* Build the result bit by bit: shift the result left, OR in the lowest bit of
* n, then shift n right. After 32 iterations the bits are mirrored. The final
* `>>> 0` reinterprets the result as an unsigned 32-bit value.
*
* Time: O(32) = O(1)
* Space: O(1)
*/
export function reverseBits(n: number): number {
let result = 0;
let value = n >>> 0;
for (let i = 0; i < 32; i++) {
result = (result << 1) | (value & 1);
value >>>= 1;
}
return result >>> 0;
}