Thursday, December 24, 2009

for programming interviews-part3

today we shall discuss a simple problems.
5.how do u find out if a no is divisible by 2 in a single line.?
int x;
x&&!(x&(x-1))

6.wap for single line swap of 2 integers without temp variable.

a^=b^=a^=b;

7.wap for finding max & min of 2 nos without branching?

min : (b-(!(a-b) &-(a < b ) ))
max : (a+(!(a-b) &-(a < b ) ))

8.wap for printing the self source code(this was asked to me in HP interview
actually the ans is quine(self printing code )
but the interviewer sed that it wasnt the answer he was expecting.
but i wrote the code for quine .he replied even a 7th grader could write tat code.....
ans:
char *f={"char*f=%c%s%c;main(){ printf(f,34,f,34,10);%c";main(){printf(f,34,f,34,10);}

9.how to print a matrix spiraaly
ans:
for(i=size(a) ,j=0;i > = 0; --i, ++j)
{
for(k=j;k < i; ++k)cout << a[j][k];
for(k=j;k < i; ++k)cout << a[k][i];
for(k=i;k > j; --k)cout << a[i][k];
for(k=j;k > j; --k)cout << a[k][j];
}
if(size(a)%2 == 0)
mid=size/2;
cout << a[mid][mid];

No comments:

Post a Comment