Browsing the archives for the Bit Manipulation category

Bit Swaps

Tweet Question: How would you find the number of bit swaps required to convert integer A to integer B? Answer: Gut instinct might suggest that you go through every bit of A and every bit of B while simultaneously updating a count of the bits that are different. But how about a cooler way to […]

Number of Ones

Tweet Question: Write a function that determines the number of bits set to 1 in the binary representation of an integer. Answer: Going by the brute force approach, it would be easy to come up with the following solution. If the least significant bit of a number is 1, it will return a result of […]

Reverse a String

Tweet Question: Reverse a string in C using as little additional memory as possible. Answer: The first solution needs the┬ásize of a char and size of two integers, all of which will be allocated from the stack. This solution is the most commonly accepted “good” solution. Here is the code. void reverseString(char* str) { int […]

Power of 2

Tweet Question: How do you find out if an unsigned integer is a power of 2? Answer: The trick here is to know that an unsigned integer which is a power of 2 has only one of its bits as 1. So a simple solution would be to loop through the bits and count the […]