1. String Format and Reverse
Intuition
Build a 32-character string of 0s and 1s representing n. Reverse the string characters. Convert the reversed string back into a 32-bit unsigned integer.
When to apply: Basic prototyping.
Algorithm
- Step 1: Pad binary string of n to length 32.
- Step 2: Reverse the string.
- Step 3: Parse reversed string as unsigned integer.
- Step 4: Return integer.
#include <iostream>#include <string>#include <bitset>#include <algorithm> using namespace std; uint32_t reverseBitsBrute(uint32_t n) { bitset<32> bs(n); string s = bs.to_string(); reverse(s.begin(), s.end()); bitset<32> rev(s); return (uint32_t)rev.to_ulong();} int main() { cout << "Brute (43261596): " << reverseBitsBrute(43261596) << endl; // 964176192 return 0;}Time & Space Complexity
- Time complexity:
O(32) = O(1) - Space complexity:
O(32) string storage