Why it works
- Bits leave n from the lowest and enter result at the lowest, while everything already in result moves up one place each round. So the first bit taken from n ends up the highest in result: the order is reversed.
- The loop runs exactly width times, not until n is 0. The zeros at the top of n become the zeros at the bottom of result: here, stopping when n hits 0 would give 13 instead of 104.
- Only shifts, & and | are used, so it works the same for any width; on LeetCode the width is 32.
Complexity
Time O(w), where w is the width: one round per bit, 32 on LeetCode, so in effect O(1). Memory O(1): two numbers.
nextNow solve it yourself, no hints.
Solve on LeetCode ↗