TCS · Question 4
Swap Odd and Even Bits
Problem
Swap odd and even bits of a number.
Approach
Mask even bits right and odd bits left, then OR.
Time O(1)Space O(1)
How it works
- 1Mask even and odd bit lanes apart.
- 2Shift toward each other and OR.
Sample input / output
Input: n = 23 (10111) Output: 43
Constraints
0 <= n < 2^32.
Solution — read it, then walk it
Time O(1)Space O(1)Returns 1source · C++
Scroll sideways for wide charts — the view follows the active step.
- start / end
- statement
- condition
- loop
- returns
- definition
1/8
StartSTART
Interactive control-flow diagram and step-by-step code walkthrough.
Recommended resourcesAffiliate links · may earn us a commission
Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits