Close

## Check if array can be divided into two parts with same XOR

Given an array of numbers, how do we check if it can be divided into two parts such that XOR values of both are same. For example consider an array A = [1, 2, 3], it can be divided into [1, 2], and  because 0001 ^ 0010 = 0011 Similarly, [8, 3, 12, 7],…

## Maximum Xor of two bit patterns

Given two numbers A, B, What is the maximum value of A’ XOR B’, where A’, B’ are obtained by permuting the binary representations of A, B respectively. For example assume A = 3, B = 1 and they are represented in 4 bits. A = 0011, B = 0001 in binary. Suppose A’ =…

## Clearing the right most set bit in a binary number

Given an integer, write a program to clear the right most set bit in it’s binary representation. For example, consider a number 54. It is represented in binary as   1 1 0 1 1 0.  The right most set bit is marked in bold. We need to convert this to  1 1 0 1…

## Finding two numbers occuring once

Given an array containing all elements twice except two numbers. Write a program to find those two numbers. For example let us consider the following array {2, 3, 2, 1, 4, 1, 4, 5} The answer is {3,5} because they appear only once and all remaining elements appear twice. This question is somewhat similar to earlier…

## Number of bits to change from one number to other

Given two numbers, calculate the number of bits required to change from one number to the other. For example 12 in binary can be represented as 1100. 15 is represented as 1111. We need to change two bits to convert one number from the other as the last two bits are different. We can find…

## Finding the unique number in an array

Given an array of numbers which contains all the numbers in pairs expect one element. We have to find that unique element. For example in the array [7,3,8,1,3,4,7,1,8] 4 is the unique element and all the remaining elements occur in pairs. This is actually a specific case of more generic problem discussed in the my…

## Printing the number in binary format

How do we write a program to print the binary representation of an integer?For the sake of simplicity, let us assume that the integer takes 32 bits. The integer 367 is represented in binary as follows.0000 0000 0000 0000 0000 0001 0110 1111Iterative Method:In this method we extract the bit at each of the 32…

## Checking if a number is power of 2

Given an integer how do we check if it is a power of 2?For example 1, 2, 4, 8, 16, 32, 64, 128, 256,… are integral powers of 2.There are several methods to check if a number is a power of 2.Method#1: Using repeated division If you repeatedly divide the number by 2 (without any…

## Counting the set bits in a number

Given an integer, how do we count the number of set (1) bits?For example the number 37 has 3 set bits in it’s binary representation (0010 0101) Method#1: Simple In this method we perform & operation between the number and 1 to get the last bit (Least Significant Bit or LSB). If it is 1…