📜  具有奇数值的二进制字符串的旋转

📅  最后修改于: 2021-04-29 11:02:34             🧑  作者: Mango

给定一个二进制字符串。我们被允许做字符串的圆形旋转而不改变字符串中的比特的相对顺序。
例如,字符串“ 011001”的所有可能的循环旋转是:

101100
010110
001011
100101
110010

我们需要通过循环旋转来告诉二进制字符串可能具有不同的奇数十进制等效项的总数。
例子:

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"]

概念:
可以看出,二进制字符串的最后一位为1时才是奇数,因为最后一位的值为2 ^ 0,因此,由于我们正在循环旋转。

C++
// CPP program to find count of rotations
// with odd value.
#include 
using namespace std;
  
// function to calculate total odd decimal
// equivalent
int oddEquivalent(string s, int n)
{
    int count = 0; 
    for (int i = 0; i < n; i++) {
        if (s[i] == '1')
            count++;
    }
    return count;
}
  
// Driver code
int main()
{
    string s = "1011011";
    int n = s.length();
    cout << oddEquivalent(s, n);
    return 0;
}


Java
// Java program to find count of rotations 
// with odd value.
  
class solution
{
static int oddEquivalent(String s, int n)
{
  
int count = 0; 
// function to calculate total odd decimal 
// equivalent 
for (int i = 0; i < n; i++) 
    { 
        if(s.charAt(i) == '1') 
            count++; 
    } 
    return count;
}
  
// Driver code
public static void main(String ar[])
{
  
String s = "1011011"; 
int n = s.length(); 
System.out.println(oddEquivalent(s, n)); 
  
}
}
//This code is contributed 
//By Surendra_Gangwar


Python3
# Python3 program to find count
# of rotations with odd value
  
#function to calculate total odd equivalent
def oddEquivalent(s, n):
    count=0
    for i in range(0,n):
        if (s[i] == '1'):
            count = count + 1
    return count
      
#Driver code
if __name__=='__main__':
    s = "1011011"
    n = len(s)
    print(oddEquivalent(s, n)) 
  
# this code is contributed by Shashank_Sharma


C#
// C# program to find count of
// rotations with odd value. 
using System;
  
class GFG 
{ 
static int oddEquivalent(String s, int n) 
{ 
    int count = 0; 
      
    // function to calculate total 
    // odd decimal equivalent 
    for (int i = 0; i < n; i++) 
        { 
            if(s[i] == '1') 
                count++; 
        } 
    return count; 
} 
  
// Driver code 
public static void Main() 
{ 
    String s = "1011011"; 
    int n = s.Length; 
    Console.WriteLine(oddEquivalent(s, n)); 
} 
} 
  
// This code is contributed 
// by Subhadeep


PHP


输出:
5