Wednesday, December 7, 2011

Problem on Bit Manipulation


Write a function to determine the number of bits required to convert integer X to integer Y.
Input: 31, 14
Output: 2


This problem seems to be quite complex, however is actually rather simple. Think about finding out which bits in two numbers are different. Simple: with an XOR.
Each 1 in the XOR will represent one different bit between X and Y. Then we can simply count the number of bits that are 1.

 public static int swapRequired(int x, int y)
{
 int counter = 0;
 for (int z = x ^ y; z!= 0; z= z>>1) {
 counter += c & 1;
 }
 return counter;
 }

Monday, December 5, 2011

Reverse a Linked List

This question is one of the most repeated ones across Google, Microsoft, Amazon and a few more. The thing which makes it a good question is that after you scratch your head and give them an algorithm they either ask you to optimize it for the boundary cases (which is fine for most of the candidates) or they ask you to do it the other way round.

I am going to give you both, recursive as well as an iterative solution. For both the techniques :

Initially call the method as : head = reverseList(head,NULL)


Iterative :

Node *Reverse (Node *p)
{
   Node *pr = NULL;
   while (p != NULL)
   {
      Node *tmp = p->next;
      p->next = pr;
      pr = p;
      p = tmp;
   }
   return pr;
}
-----------------------------------------------------------------------
Recursive:

Node *reverseList(Node *current, Node *parent)
{
        Node *revHead;
   if(current == null)
      revHead = parent;
   else
   {
      revHead = reverseList(current->next,current);
      current->next = parent;      
   }
   return revHead;
}

Saturday, December 3, 2011

Easy-4


void main()
{
int *mptr, *cptr;
mptr = (int*)malloc(sizeof(int));                               //Output: some garbage values
printf(“%d”,*mptr);
int *cptr = (int*)calloc(sizeof(int),1);                      // Output=0
printf(“%d”,*cptr);
}

The above statements return garbage values and a zero in the next.
So much for understanding a small difference between malloc() and calloc().
See the differences in arguments and the returned values.

Friday, December 2, 2011

A few simple logical questions !


1.) 

Multiplying a number by 7 without using * and + operators.

NewNum = Num << 3;                      // multiplied by 2^3 = 8

NewNum = NewNum - Num;             // 8 – 1 = 7

2.)

Finding the last character of any String.
                              (OR)

Write a function that finds the last instance of a character in a string


char *lastChar(char *String, char ch)
{
char *cStr = NULL;


// traverse the entire string


while(*String ++ != NULL ) 
{
if(*String==ch) 
cStr = String;
}
return cStr;