Rotations of a Binary String with Odd Value
Last Updated :
30 Nov, 2022
Given a binary string. We are allowed to do circular rotation of the string without changing the relative order of the bits in the string.
For Example, all possible circular rotation of string “011001” are:
101100
010110
001011
100101
110010
We are required to tell total number of distinct odd decimal equivalent possible of binary string, by doing circular rotation.
Examples:
Input : 011001
Output : 3
Explanation:
All odd possible binary representations are:
["011001", "001011", "100101"]
Input : 11011
Output : 4
Explanation:
All odd possible binary representations are:
["11011", "01111", "10111", "11101"]
Concept: It can be observed that a binary string can only be odd if it’s last bit is 1, because the value of the last bit is 2^0.Hence, since we are doing the circular rotation.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
int oddEquivalent(string s, int n)
{
int count = 0;
for ( int i = 0; i < n; i++) {
if (s[i] == '1' )
count++;
}
return count;
}
int main()
{
string s = "1011011" ;
int n = s.length();
cout << oddEquivalent(s, n);
return 0;
}
|
Java
class solution
{
static int oddEquivalent(String s, int n)
{
int count = 0 ;
for ( int i = 0 ; i < n; i++)
{
if (s.charAt(i) == '1' )
count++;
}
return count;
}
public static void main(String ar[])
{
String s = "1011011" ;
int n = s.length();
System.out.println(oddEquivalent(s, n));
}
}
|
Python3
def oddEquivalent(s, n):
count = 0
for i in range ( 0 ,n):
if (s[i] = = '1' ):
count = count + 1
return count
if __name__ = = '__main__' :
s = "1011011"
n = len (s)
print (oddEquivalent(s, n))
|
C#
using System;
class GFG
{
static int oddEquivalent(String s, int n)
{
int count = 0;
for ( int i = 0; i < n; i++)
{
if (s[i] == '1' )
count++;
}
return count;
}
public static void Main()
{
String s = "1011011" ;
int n = s.Length;
Console.WriteLine(oddEquivalent(s, n));
}
}
|
PHP
<?php
function oddEquivalent( $s , $n )
{
$count = 0;
for ( $i = 0; $i < $n ; $i ++)
{
if ( $s [ $i ] == '1' )
$count ++;
}
return $count ;
}
$s = "1011011" ;
$n = strlen ( $s );
echo (oddEquivalent( $s , $n ));
?>
|
Javascript
<script>
function oddEquivalent(s, n)
{
var count = 0;
for ( var i = 0; i < n; i++) {
if (s[i] == '1' )
count++;
}
return count;
}
var s = "1011011" ;
var n = s.length;
document.write( oddEquivalent(s, n));
</script>
|
Time Complexity: O(n), where n is the length of the given string.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Share your thoughts in the comments
Please Login to comment...