Category Archives: Bit Magic

Bitwise and (or &) of a range

Given two non-negative long integers, x and y given x <= y, the task is to find bit-wise and of all integers from x and y, i.e., we need to compute value of x & (x+1) & … & (y-1) & y.7 Examples: Input : x = 12, y = 15 Output : 12 12… Read More »

Multiples of 4 (An Interesting Method)

Given a number n, the task is to check whether this number is a multiple of 4 or not without using +, -, * ,/ and % operators. Examples: Input: n = 4 Output – Yes n = 20 Output – Yes n = 19 Output – No Method 1 (Using XOR) An interesting fact… Read More »

Equal Sum and XOR

Given a positive integer n, find count of positive integers i such that 0 <= i <= n and n+i = n^i Input : n = 7 Output : 1 Explanation: 7^i = 7+i holds only for only for i = 0 7+0 = 7^0 = 7 Input n = 12 Output: 4 12^i =… Read More »

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 »