Category Archives: Bit Magic

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.

Check if a given number is sparse or not

A number is said to be a sparse number if in binary representation of the number no two or more consecutive bits are set. Write a function to check if a given number is Sparse or not.

Find nth Magic Number

A magic number is defined as a number which can be expressed as a power of 5 or sum of unique powers of 5. First few magic numbers are 5, 25, 30(5 + 25), 125, 130(125 + 5), ….