Maximum number of splits of a binary number
Given a binary string S, the task is to find the maximum number of parts that you can split it into such that every part is divisible by 2. If the string can’t be split satisfying the given conditions then print -1.
Examples:
Input: S = “100”
Output: 2
The splits are as follows:
“10” ans “0”.
Input: S = “110”
Output: 1
Approach: This problem can be solved greedily, start from the left end and put a cut at an index j such that j is the smallest index for which sub-string upto j is divisible by 2. Now, continue this step with the rest of the left-over string. It is also known that any binary number ending with a 0 is divisible by 2. Thus, put a cut after each and every zero and the answer will be equal to the number of zeros in the string. The only case where the answer is not possible is when the given string is odd i.e. no matter how cuts are made on the string, the last split part will always be odd.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int cntSplits(string s)
{
if (s[s.size() - 1] == '1' )
return -1;
int ans = 0;
for ( int i = 0; i < s.size(); i++)
ans += (s[i] == '0' );
return ans;
}
int main()
{
string s = "10010" ;
cout << cntSplits(s);
return 0;
}
|
Java
class GFG
{
static int cntSplits(String s)
{
if (s.charAt(s.length() - 1 ) == '1' )
return - 1 ;
int ans = 0 ;
for ( int i = 0 ; i < s.length(); i++)
ans += (s.charAt(i) == '0' ) ? 1 : 0 ;
return ans;
}
public static void main(String []args)
{
String s = "10010" ;
System.out.println(cntSplits(s));
}
}
|
Python3
def cntSplits(s) :
if (s[ len (s) - 1 ] = = '1' ) :
return - 1 ;
ans = 0 ;
for i in range ( len (s)) :
ans + = (s[i] = = '0' );
return ans ;
if __name__ = = "__main__" :
s = "10010" ;
print (cntSplits(s));
|
C#
using System;
class GFG
{
static int cntSplits(String s)
{
if (s[s.Length - 1] == '1' )
return -1;
int ans = 0;
for ( int i = 0; i < s.Length; i++)
ans += (s[i] == '0' ) ? 1 : 0;
return ans;
}
public static void Main(String []args)
{
String s = "10010" ;
Console.WriteLine(cntSplits(s));
}
}
|
Javascript
<script>
function cntSplits(s)
{
if (s[s.length - 1] == '1' )
return -1;
var ans = 0;
for ( var i = 0; i < s.length; i++)
ans += (s[i] == '0' );
return ans;
}
var s = "10010" ;
document.write( cntSplits(s));
</script>
|
Time Complexity: O(|s|)
Auxiliary Space: O(1)
Last Updated :
09 Nov, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...