Category Archives: Bit Magic

Find profession in a special family

Consider a special family of Engineers and Doctors with following rules : Everybody has two children. First child of an Engineer is an Engineer and second child is a Doctor. First child of an Doctor is Doctor and second child is an Engineer. All generations of Doctors and Engineers start with Engineer. We can represent… Read More »

Print first n numbers with exactly two set bits

Given a number n, print first n positive integers with exactly two set bits in their binary representation. Examples: Input: n = 3 Output: 3 5 6 The first 3 numbers with two set bits are 3 (0011), 5 (0101) and 6 (0110) Input: n = 5 Output: 3 5 6 9 10 12 A… Read More »

Generate 0 and 1 with 25% and 75% probability

Given a function rand50() that returns 0 or 1 with equal probability, write a function that returns 1 with 75% probability and 0 with 25% probability using rand50() only. Minimize the number of calls to rand50() method. Also, use of any other library function and floating point arithmetic are not allowed. The idea is to… Read More »

Find even occurring elements in an array of limited range

Given an array that contains odd number of occurrences for all numbers except for a few elements which are present even number of times. Find the elements which have even occurrences in the array in O(n) time complexity and O(1) extra space. Assume array contain elements in the range 0 to 63. Examples: Input: [9,… Read More »

Cyclic Redundancy Check and Modulo-2 Division

CRC or Cyclic Redundancy Check is a method of detecting accidental changes/errors in communication channel. CRC uses Generator Polynomial which is available on both sender and receiver side. An example generator polynomial is of the form like x3 + x + 1. This generator polynomial represents key 1011. Another example is x2 + 1 that… Read More »

Check if a number is Bleak

A number ‘n’ is called Bleak if it cannot be represented as sum of a positive number x and set bit count in x, i.e., x + countSetBits(x) is not equal to n for any non-negative number x. Examples : Input : n = 3 Output : false 3 is not Bleak as it can… Read More »

Count strings with consecutive 1’s

Given a number n, count number of n length strings with consecutive 1’s in them. Examples: Input : n = 2 Output : 1 There are 4 strings of length 2, the strings are 00, 01, 10 and 11. Only the string 11 has consecutive 1’s. Input : n = 3 Output : 3 There… Read More »

C++ bitset and its application

A bitset is an array of bool but each Boolean value is not stored separately instead bitset optimizes the space such that each bool takes 1 bit space only, so space taken by bitset bs is less than that of bool bs[N] and vector bs(N). However, a limitation of bitset is, N must be known… Read More »