Count Substrings Starting And Ending With 1

PROBLEM :

Given a binary string, count number of substrings that start and end with 1. For example, if the input string is “00100101”, then there are three substrings “1001”, “100101” and “101”.

Input:
The first line contains T denoting the number of testcases. Then follows description of testcases.
Each case contains a string containing 0's and 1's.


Output:
For each test case, output a single line denoting number of substrings possible.

Constraints:
1<=T<=100
1<=Lenght of String<=100


Example:
Input:
1
10101

Output:
3
     
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

#include<iostream>
using namespace std;
#include<string.h>
int Count_Substrings(char *) ;
int main()
 {
int t,count;
char str[100] ;
cin>>t ;
while(t--)
{
   cin>>str ;
   count=0 ;
   count=Count_Substrings(str) ;
   cout<<count<<endl ;
}
return 0;
}

int Count_Substrings(char *str)
{
    int count ,i,l,j ;
    l=strlen(str) ;
    count=0 ;
    for(i=0;i<l;i++)
    {
        if(str[i]=='1')
        {
            for(j=i+1;j<l;j++)
            {
                if(str[j]=='1')
                    count++ ;
            }
        }
    }
    return count ;
}

--------------------------------------------------------------------------------
BETTER SOLUTION :
--------------------------------------------------------------------------------

#include<iostream>
using namespace std;
#include<string.h>
int Count_Substrings(char *) ;
int main()
 {
int t,count;
char str[100] ;
cin>>t ;
while(t--)
{
   cin>>str ;
   count=0 ;
   count=Count_Substrings(str) ;
   cout<<count<<endl ;
}
return 0;
}

int Count_Substrings(char *str)
{
    int count,i,l ;
    l=strlen(str) ;
   
    count=0 ;
    for(i=0;i<l;i++)
    {
        if(str[i]=='1')
            count++ ;
    }
   
    return count*(count-1)/2 ;
}

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

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )