Category Archives: Bit Magic

Check whether a given number is even or odd

Given a number, check whether it is even or odd. Examples: input: 2 output: even input: 5 output: odd One simple solution is to find remainder after dividing by 2. Odd A better solution is to use bitwise operators. We need to check whether last bit is 1 or not. If last bit is 1… Read More »

Find Two Missing Numbers | Set 2 (XOR based solution)

Given an array of n unique integers where each element in the array is in range [1, n]. The array has all distinct elements and size of array is (n-2). Hence Two numbers from the range are missing from this array. Find the two missing numbers. Examples: Input : arr[] = {1, 3, 5, 6},… Read More »

C++ bitset interesting facts

Bitset is a container in C++ Standard Template Library for dealing with data at the bit level. A bitset stores bits (elements with only two possible values: 0 or 1). We can however get the part of a string by providing positions to bitset constructor (Positions are with respect to string position from left to… Read More »

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 »