• Adding 2 Binary numbers:

One of the popular interview questions, usually in the preliminary or the telephonic rounds. Given 2 binary arrays of length, you need to find their sum?

Ans: The arrays can be initialized as java boolean types,
Eg:

                boolean A[] = { true, false, false };
		boolean B[] = { true, false, false };
		boolean C[] = { false, false, false, false };
		boolean carry = false;
		for (int j = B.length - 1; j >= 0; j--) 
		{
			C[j + 1] = ((A[j] ^ B[j]) ^ carry);
			if (A[j] && B[j]) 
			{
				carry = true;
			} 
			else 
			{
				carry = false;
			}

		}
		C[0] = carry;

		return C;

The Sum can be calculated by using the XOR operator with a carry.

 

  • Finding the unique number from a given array:

Given an array, which has a double of each number(1,1,2,3,2,3,4,4…….). Find a single Number which is unique?

Brute-Force approach: Walk through the array and compare the numbers using a counter variable or something similar.

Simple Approach: XOR the array. Only the unique number will remain.

 

  • Find if the number ‘n’ i s a power of 2 or not.

n & (n – 1) == 0 should be true.

Advertisements