Category Archives: Bit Magic

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 »

Sum of Bitwise And of all pairs in a given array

Given an array “arr[0..n-1]” of integers, calculate sum of “arr[i] & arr[j]” for all the pairs in the given where i < j. Here & is bitwise AND operator. Expected time complexity is O(n). Examples: Input: arr[] = {5, 10, 15} Output: 15 Required Value = (5 & 10) + (5 & 15) + (10… Read More »

Find Next Sparse Number

A number is Sparse if there are no two adjacent 1s in its binary representation. For example 5 (binary representation: 101) is sparse, but 6 (binary representation: 110) is not sparse. Given a number x, find the smallest Sparse number which greater than or equal to x. Examples: Input: x = 6 Output: Next Sparse… Read More »

Find XOR of two number without using XOR operator

Given two integers, find XOR of them without using XOR operator, i.e., without using ^ in C/C++. Examples: Input: x = 1, y = 2 Output: 3 Input: x = 3, y = 5 Output: 6 We strongly recommend you to minimize your browser and try this yourself first. A Simple Solution is to traverse… Read More »

Sum of bit differences among all pairs

Given an integer array of n integers, find sum of bit differences in all pairs that can be formed from array elements. Bit difference of a pair (x, y) is count of different bits at same positions in binary representations of x and y.