Wednesday, 15 November 2017

Recursive function that decodes a string of 0's and 1's into a two-digit number.



Write a recursive function that decodes a string of 0's and 1's into a two-digit number. The input string will consist of a sequence of 0's - representing the first digit, followed by a sequence of 1's - representing the second digit.


For example, the string: "0001111"
Represents the number 34

Solution:
#include <stdio.h>
void rec(char *st, int i, int c,int d)
{
    if(st[i] == '\0')
        printf("%d %d",c,d);
    if(st[i] == '0')
        rec(st,i+1,c+1,d);
    if(st[i] == '1')
        rec(st,i+1,c,d+1);
}           
int main()
{
    char st[8];
    scanf("%s",st);
    rec(st,0,0,0);
    return 0;
}


No comments:

Post a Comment