Swap bits
EasyGiven 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: 1100i = 1j = 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
Solution
6 Essential Primitives Coding Interview Problems
Master Primitives by trying the coding challenges below.
- 1.Swap bitsEasy
- 2.Power of twoEasy
- 3.Count bitsMedium
- 4.Reverse bitsMedium
- 5.Find duplicateMedium
- 6.Bitwise additionHard