Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

implement atoi() of C in PHP [closed]

There's a function in C, atoi(), implement this in PHP;

  • $string = '5467'; //function should return 5467 as integer

So this is what I found (its implementation in C)

int myatoi(const char *string) {
    int i;
    i=0;
    while(*string) {
        i = (i<<3) + (i<<1) + (*string - '0');
        string++;
    }
like image 254
vknyvz Avatar asked Nov 15 '12 01:11

vknyvz


3 Answers

Unless I am misunderstanding the question:

function atoi($string)
{
  return (int) $string;
}

It sounds like a trick question to see if you understand the concept of php as a loosely typed language. So yes, it's fair to ask.

like image 94
jeroen Avatar answered Sep 20 '22 22:09

jeroen


I don't know PHP but if the point was to see if you could write the algorithm, I can show how I'd approach this in C. (Untested code here.)

int atoi(char *s)
{
    int val = 0;
    while (*s)
    {
        val *= 10;
        val += (*s) - '0';
        s++;
    }
    return val;
}
like image 30
Jonathan Wood Avatar answered Sep 21 '22 22:09

Jonathan Wood


It's really just:

function myatoi($s) {
    return (int) $s;
}

I think it's a good think that they are looking for your problem solving skills. A good senior developer would probably come up with the following interesting observations:

  • What should my function return if the data is not valid (eg: "a"). 0? Throw an exception? Your C example will return some garbage (even for "15a", for which the standard says you should return 15).
  • Your C example cannot handle negative numbers.
  • What should be the result if the number doesn't fit into an integer? Your C example will simply overflow (which is BTW completely valid in C).
like image 41
Karoly Horvath Avatar answered Sep 21 '22 22:09

Karoly Horvath