← TCS bank

TCS · Question 4

Swap Odd and Even Bits

C++code⏱ O(1)💾 O(1)
Service-based

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

  1. 1Mask even and odd bit lanes apart.
  2. 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.
STARTinclude <iostream>include <cstdint>using namespace stduint32_t swapBits(uint32_tn)DEFINE main()cout << swapBits(23) <<endlRETURN 0END
  • 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