Search code examples
phpcalgorithmatoi

implement atoi() of C in PHP


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++;
    }

Solution

  • 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;
    }