Adobe Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: In-Person
bool isnotEqual(int a, int b)
{
int i=0;
loop(a)
{
increment(1); //increment i
}
loop(b)
{
increment(-1); //decrease i
}
if( i)
return true;
else
return false;
}
int result(a,b)
{
diff =0;
while(isnotEqual(a,b))
{
increment(1) //a++;
diff++;
}
return diff;
}
it will work correctly only if a<b
We can solve this using the approach that first take zero and decrement it to b times. Now to make the number negative we can use the logic of the way integer implemented. That suppose if integer is 8 bit long then its range is defined as -128 to 127 and it is cyclic; means when we increment 0 to 255 times it gives -1 and not 255. So using this logic Algo will be
int num =0;
loop(b)
{
loop(INT_MAX)
{
increment(num);
}
}
loop(a)
{
increment(num);
}
result=num;
Code for the same {loop is general for loop and increment operator, otherwise you can implement you own Loop(a) and increment(a) :) }
int main()
{
int i,j,l=0,a=8,b=5;
for(i=0;i<b;i++)
{
for(j=0;j<2147483647;j++)
l++;
l++;
for(j=0;j<2147483647;j++)
l++;
}
printf("\n%d",l);
for(i=0;i<a;i++)
l++;
printf("\n%d",l);
return 0;
}
in this solution here i have taken integer as 32 bit long and while looping in for loop i can compare j to (INT_MAX/2)-1 times otherwise it will go in infinite loop.... so one additional L++ required after the loop..... and one additional loop for other half rotation.....
int result(int a, int b)
{
int i,j=0;
for(i=a,j;i>b;i--,j++);
return j;
}
it'll work only if a>b
we don't have ++ and -- operators so we can't use those, in my solution above if you see i have given the logic first, using loop(n) and increment(n) but to check if logic works we had to use inbuilt for loop to implement loop and increment .... otherwise had to implement loop and increment separately... din't use it for logic implementation.... and it works for all if a > or < or = b
But what you are doing here is just making use of ++ and -- operator to implement the a-b ,c heck pls....
#include<iostream.h>
#define Increment(count) count++
#define Loop(count) for(int k=0;k<count;k++)
void Decrement(int &A)
{
int i,j;
i=0;j=0;
Loop(A)
{
j=i;
Increment(i);
}
A=j;
cout<<"A="<<A<<" i="<<i<<" j="<<j<<endl;
}
void main()
{
int A=10,B=6;
Loop(B)
{
Decrement(A);
}
cout<<"A="<<A<<endl;
}
Forgot to mention A and B are integers..... so function will be something like
- mangal.govind April 11, 2012int result(int a,int b) so for a=5,b=3 it returns 2.