Programmer Interview 101
Every programmer knows that a good programmer can create a code even if he doesn't memorized his syntax. Technically it is the same as a good programmer knows how to adapt on the language because what he is capable of is generating an algorithm.

Now on every job interview or technical examination on this field, the ability on how to formulate an algorithm is always tested. The good thing about this is that some of the questions are already been leaked out and so all you need to do is to study the flow of their logic.

So why am I posting this one? Well, I thought of sharing some of the most common questions and answer for this questions. Actually, I was a victim of these so now I thought of sharing most of them :)

Without further adieu, here is the exact question that was asked to me 4 years ago.

Part 1 - Create a function that will convert a string to its integer value without using any library functions.


Analysis
Just for this example, I'll be using a C type programming syntax. Since we are dealing on the algorithm, I'll just explain it later on how does it work.

When we say library files it means all the shorthand functions will not be used.

The Code
int stringToInt(char str[])  
{  
    int i=0,total=0;  
    while(str[i]!='\0'){  
         if(str[i]< 48 || str[i] > 57){  
             printf("One character is invalid.\n");  
             return 0;  
         }  
         else  
         {  
             total = total*10 + (str[i] - 48);  
             i++;  
         }  
  
    }  
  
    return total;  
  
}


The Algorithm

First we need to know that a single character is compose of 1 byte or 8 bits.

Now if we represent the characters 0 to 9 as bits in decimal format (ref. ASCII Table), we can say that 0 is equivalent to 48 (decimal), with 1 == 49, 2 == 50 and so on up to 57 == 9. Bearing that in mind, what we need to do is to create a code or an equation that makes the decimal equivalent of each character equal to the decimal value of its integer.

This line of code:

total = total*10 + (str[i] - 48);  

converts each character in the string to to its integer equivalent. What it does is to subtract 48 (decimal) to the character (or you can also do some bitwise operations on some languages such as ANDing it to 15 based 10) to get the integer equivalent.

5 comments :

  1. Nice one. :D
    I might have to deal with this in the future. XD

    ReplyDelete
  2. I always remember what you told me dude.

    "Be the master of algorithm."  :)

    ReplyDelete
  3. well it's really true :)

    ReplyDelete
  4. well in case you have any experience similar to this during your technical exam on this career, I hope you can share it too :)

    ReplyDelete
  5. Gandang gabi po, dumaan lang ulit ako. ^_^

    ReplyDelete