Labels

Friday, September 16, 2011

character to integer

problem : implement atoi function

declaration : int atoi(char*s);

solution 1 : (left to right )

int atoi(char*s)
{
    int valuesofar=0;
    if(s)
    {    
	while(*s && *s>='0' && *s<='9')
   	{
       		valuesofar = valuesofar*10 + (*s-'0');
       		s++;
   	}
    }
   return valuesofar;
}

solution 2: (right to left )
int atoi(char*s)
{
    int valuesofar=0;
    int power=1;
    char*x;
    if(s)
    {   
	x = s;
	while(*x)
	x++;            // reach the end of the string
  
	while(x>=s&& *x>='0' && *x<='9')
   	{
       		valuesofar += (*x-'0') * power ;
       		x--;
		power*=10;           // adjust power
   	}
    }
   return valuesofar;
}

No comments:

Post a Comment