Coding challenges
In the next 25 coding challenges, we will exploit different aspects of bit manipulations. Since these kinds of problems are really brain-teasing, they are preferred in interviews. Understanding a snippet of code that manipulates bits is not an easy task, so take your time and dissect each problem and snippet of code. This is the only way to obtain some patterns and templates in order to solve these kinds of problems.
The following figure contains a set of four bit-mask that are important to have in your toolbelt:
They can be useful for solving a variety of problems where you need to manipulate bits.
Coding challenge 1 – Getting the bit value
Problem: Consider a 32-bit integer, n. Write a snippet of code that returns the bit value of n at the given position, k.
Solution: Let's consider that n=423. Its binary representation is 110100111. How can we say what the value of the bit at position...