ยท 1 min read
Blind 75 - Reverse Bits
Get the last bit of value from the original. append to the reverse one. shift reverse one to the left. instead of adding, you can do `or` because after the shift last value will be 0. Imp - iterate 32 times only.
[Video]
Reverse the binary int
Read this for java instruction: Link
Approaches
O(1) time; O(1) space; 7 lines
Get the last bit of value from the original. append to the reverse one. shift reverse one to the left. instead of adding, you can do or because after the shift last value will be 0. Imp - iterate 32 times only.
public int reverseBits(int n) {
int rev = 0;
for (int i = 0; i < 32; i++) {
rev = (rev << 1) + (n&1);
n = n>>1;
}
return rev;
}Related posts
- Blind 75 - Number of 1 Bits Nov 16, 2022
- Blind 75 - Invert Binary Tree Nov 16, 2022
- Blind 75 - Linked List Cycle Nov 16, 2022
Get new posts by email
No spam. Unsubscribe anytime. Or grab the RSS feed.
Mailto-based for now. ButtonDown / ConvertKit can replace this form later.