C Programming – HackerRank Solution | Find the N-th character |

(HackerRank) Write a Modular C Programming code to solve Find the N-th character, Given a binary string S . Perform R iterations on string S, where in each iteration 0 becomes 01 and 1 becomes 10

Given a binary string S . Perform R iterations on string S, where in each iteration 0 becomes 01 and 1 becomes 10. Find the Nth character of the string after performing these R iterations.

Input Format

First line contains the binary string consisting of 0’s and 1’s.

Second line contains R number of iterations

Third line contains N, Nth character to be found out.

Constraints

1 ≤ String length ≤ 100 1 ≤ R ≤ 20 0 ≤ N < Length of final string

Output Format

Display the Nth character in a single line

Sample Input 0

101
2
3

Sample Output 0

1

Explanation 0

 After 1st iteration string becomes 100110.
 After 2nd iteration, string = 100101101001
 After 2nd iteration we can clearly see that the 3rd character is 1. (character number starts from 0)

Refer : C Programming HackerRank all solutions for Loops | Arrays | strings

 

CODE:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>

int main() {
    char str[200],str2[200];
    int k,n,i;
    scanf("%s",str);
    scanf("%d%d",&k,&n);
    while(k>0)
    {
        i=0;
        while(str[i]>0)
        {
            str2[2*i]=str[i];
            if(str[i]=='1')
                str2[(2*i)+1]='0';
            else //if(str[i]=='0')
                str2[(2*i)+1]='1';
            i++;
        }
        str2[2*i]='\0';
        //printf("%s\n",str2);
        strcpy(str,str2);
        k--;
    }
    printf("%c",str[n]);
    return 0;
}


OUTPUT

Congratulations, you passed the sample test case.

Click the Submit Code button to run your code against all the test cases.

Input (stdin)

101
2
3
Your Output (stdout)

1
Expected Output

1

 

Please find some more codes of Loops, Condition Statements, 1D Arrays, 2D Arrays, Strings, Pointers, Data Structures, Files, Linked lists, MISC, Solved model question papers & Hacker Rank all solutions on the below page:

Top 100+ C Programming codes – KLE Technological University

Leave a Comment