Fog Creek Software
Discussion Board




int atoi( char* pStr )

Hey!

i have a simpler solution than the one given  at

http://techinterview.org/Solutions/fog0000000098.html

--------------------------------------------------------------------
#include <stdio.h>

int main()
{
  char *string="10005678";
  printf("\nNumber -> [%d]\n",myatoi(string));
  return(0);
}


int myatoi(char *s)
{
  int i=0;
  while(*s)
  {
    i = (i<<3) + (i<<1) + (*s-'0');
    s++;
  }
  return(i);
}

--------------------------------------------------------------------

Bhushan

Srirang Bhushan
Sunday, February 13, 2005

How is

(i<<3) + (i<<1)

simpler than

i*10 ?

Other than that your answer is identical, except that you don't have any error checking.

Joel Spolsky
Sunday, February 13, 2005

My idea was to have a simple formula which scans from the L->R (the way most people think one should scan a string) and give the answer.

Yes, it does not have terrific error handling, but thats very simple to add.

Srirang Bhushan
Monday, February 14, 2005

Uh, I think you didn't read to the bottom. The left-to-right solution is already there...

Joel Spolsky
Fog Creek Software
Monday, February 14, 2005

*  Recent Topics

*  Fog Creek Home