Count of 1-bit and 2-bit characters in the given binary string
Given two special characters, the first character can be represented by one bit which is 0 and the second character can be represented by two bits either 10 or 11. Now given a string represented by several bits. The task is to return the number of characters it represents. Note that the given string is always valid.
Examples:
Input: str = “11100”
Output: 3
“11”, “10” and “0” are the required characters.
Input: str = “100”
Output: 2
Approach: The approach to solve the problem is that if the current character is 0 then it represents a single character of 1 bit but if the current character is 1 then the next bit after it has to be included in the character consisting of two bits as there is no single bit characters starting with 1.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countChars(string str, int n)
{
int i = 0, cnt = 0;
while (i < n) {
if (str[i] == '0' )
i++;
else
i += 2;
cnt++;
}
return cnt;
}
int main()
{
string str = "11010" ;
int n = str.length();
cout << countChars(str, n);
return 0;
}
|
Java
class GFG {
static int countChars(String str, int n)
{
int i = 0 , cnt = 0 ;
while (i < n) {
if (str.charAt(i) == '0' )
i += 1 ;
else
i += 2 ;
cnt += 1 ;
}
return cnt;
}
public static void main (String[] args)
{
String str = "11010" ;
int n = str.length();
System.out.println(countChars(str, n));
}
}
|
Python3
def countChars(string, n) :
i = 0 ; cnt = 0 ;
while (i < n) :
if (string[i] = = '0' ):
i + = 1 ;
else :
i + = 2 ;
cnt + = 1 ;
return cnt;
if __name__ = = "__main__" :
string = "11010" ;
n = len (string);
print (countChars(string, n));
|
C#
using System;
class GFG
{
static int countChars( string str, int n)
{
int i = 0, cnt = 0;
while (i < n)
{
if (str[i] == '0' )
i += 1;
else
i += 2;
cnt += 1;
}
return cnt;
}
public static void Main ()
{
string str = "11010" ;
int n = str.Length;
Console.WriteLine(countChars(str, n));
}
}
|
Javascript
<script>
function countChars(str, n)
{
let i = 0, cnt = 0;
while (i < n)
{
if (str[i] == '0' )
i += 1;
else
i += 2;
cnt += 1;
}
return cnt;
}
let str = "11010" ;
let n = str.length;
document.write(countChars(str, n));
</script>
|
Time complexity: O(n) where n is length of given binary string
Auxiliary space: O(1) because it is using constant space for variables
Last Updated :
16 Nov, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...