Qualcomm Interview Question Software Engineer in Tests
0of 0 votesCount the bits in a Integer, Swap two numbers without using any temp variable, Find the middle element in the linked list
Country: United States
Interview Type: In-Person
Q2.)
let two numbers are a and b, they can be swapped like below
a = a + b
b = a - b
a = a - b
Q3.)
Maintain two pointers slow and fast.
Iterate thru the list by moving slow pointer once and fast pointer twice. When fast pointer will point to null, slow pointer will be pointing to middle element.
answer to Q2 is wrong.
Step 1 : a = a + b
This step may result into an overflow which is not supported.
Remember, you are not writing a mathematical equation, it is an ALGO.
Q2.
I think this is almost right...
Line:
b = a - b
will implicitly perform an operation in another variable. E.g.:
c = a - b
b = c
To make it independent of any temporaries, have the variable that is set, be the left operator on the right side of the equation.
a = a + b // or a += b
b = -b
b = b + a // or b += a
a = a - b // or a -= b
This is what it would look like in pseudo-assembly language:
add a, b
neg b
add b, a
sub a, b
No temps used anywhere :)
Q1)
int count_bits(int n)
{
int x = 1;
int res = 0;
while(x < n)
{
if( n & x != 0 )
res++;
x = x << 1;
}
return res;
}

To swap two numbers w/o using a temp variable, use XOR (^):
- Anonymous on February 27, 2012 Edit | Flag Replya = a ^ b
b = a ^ b
a = a ^ b
Try it with this and see for yourself:
a = 0011
b = 0101