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

fair result from an unfair coin

you are given an unfair coin in which head has higher probability of occurring than tails.

solution :

assume

TH as head
HT as tail
TT, HH than toss again

now new head and tail have equal probabilities

Using bit vectors

a nice discussion on why one should use bit vectors and not integer arrays in some particular situations

bit vector

Wednesday, September 7, 2011

print a unsigned long int using putchar

problem : print an unsigned long integer using only putchar

solution : we'll have to break the number and print the individual digit, we can use % operation to get the digits

code :

void putlong(unsigned long n) {
  if (n < 10) {
    putchar(n + '0');
    return;
  }
  putlong(n / 10);
  putchar(n % 10 + '0');
}

reverse a string using recursion

problem : reverse a string using recursion

: solution

void print_reverse(char* str)
{
	if(*str=='\0')return;
	else
	print_reverse(str+1)
	putchar(*str);
}