Stack Bash - Master data structures and algorithms

Swap bits

Given an n-bit binary number and two bit indices i and j, where the 0th index is the least significant bit, and n is the most significant bit.
Write a function that swaps the input's bits i and j and returns the resulting number.
For example, given the following inputs:
num = 12 # binary: 1100
i = 1
j = 3
Your function should return 6, or the binary number 0110.
Use the decimal-to-binary converter below and run through additional examples.

Try it first


6 Essential Primitives Coding Interview Problems

Master Primitives by trying the coding challenges below.
  1. 1.Swap bitsEasy
  2. 2.Power of twoEasy
  3. 3.Count bitsMedium
  4. 4.Reverse bitsMedium
  5. 5.Find duplicateMedium
  6. 6.Bitwise additionHard

Want to confidently pass your next coding interview?

Stack Bash helps new and veteran software engineers master data structures and algorithms for technical interviews.