HCL Interview Question
Developer Program EngineersCountry: India
Interview Type: Written Test
in my view the result can be obtained by (36*100)+12=3612.
But since arithmetic operation are not allowed so we first break 100 into sum of power of 2s
i.e. 100=(64+32+4)
Now, 36 can be multiplied by 64,32 and 4 using bit operators such as
let d1=36<<6;
d2=36<<5
d3=36<<2;
now d1, d2 d3 can be added again using bitwise operator using concept of half adder
Since finally we will get a=3600;
again using half adder concept we can easily add 12 to it
and hence obtain 3612.
halfadder(int a,int b)
{
a=a^b;
if((a&b)==0)
{
break;
}
b=a&b;
b=b<<1;
}
Sorry, my halfadder logic is little wrong;
int Add(int x, int y)
{
// Iterate till there is no carry
while (y != 0)
{
// carry now contains common set bits of x and y
int carry = x & y;
// Sum of bits of x and y where at least one of the bits is not set
x = x ^ y;
// Carry is shifted by one so that adding it to x gives the required sum
y = carry << 1;
}
return x;
}
// sorry for the mistake . Actually this is my 1st attempt for an answer . I hope no one minds it
Here is the algorithm.
1. First find the number of digits in first operand 'a' ( this is equal to the power of 10)
2. We need to multiply this power of 10 with the second operand 'b'.
3. Then OR (|) result from step 2 and the first operand 'a'.
public class Concatenate {
public static void main(String[] args) {
int a = 12;
int b = 36;
int digit_count = (int) Math.log10(a)+1; // To find the number of digits in first operand
int c = 0;
switch(digit_count){
case 1 : // Power of 10 is 1.
c = (b << 3) + (b << 1); // 10^1(10) = 2^3(8)+ 2^1(2)
break;
case 2 : // Power of 10 is 2.
c = (b << 6) + (b << 5)+ (b << 2); // 10^2(100) = 2^6(64)+ 2^5(32)+ 2^2(4)
break;
}
c = c | a; // Add the both the values to get the output.
System.out.println(c); // Outputs 3612
}
}
Here is my solution using macros.
- goldentss July 02, 2015