📌  相关文章
📜  给定二进制字符串可被2整除的子字符串数

📅  最后修改于: 2021-05-04 08:23:58             🧑  作者: Mango

给定长度为N的二进制字符串str ,任务是找到被2整除的str子字符串的计数。子字符串中允许前导零。
例子:

天真的方法:天真的方法将生成所有可能的子字符串,并检查它们是否可被2整除。其时间复杂度为O(N 3 )。
高效的方法:可以观察到,只有二进制数字以0结束时,它才能被2整除。现在,任务是只计算以0结尾的子字符串的数量。因此,对于每个使str [i] =’0’的索引i ,找到以i结尾的子串的数量。该值等于(i + 1) (基于0的索引)。因此,最终答案将等于所有i(i +1)之和,这样str [i] =’0′
下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to return the count
// of the required substrings
int countSubStr(string str, int len)
{
    // To store the final answer
    int ans = 0;
 
    // Loop to find the answer
    for (int i = 0; i < len; i++) {
 
        // Condition to update the answer
        if (str[i] == '0')
            ans += (i + 1);
    }
 
    return ans;
}
 
// Driver code
int main()
{
    string str = "10010";
    int len = str.length();
 
    cout << countSubStr(str, len);
 
    return 0;
}


Java
// Java implementation of the approach
class GFG
{
     
    // Function to return the count
    // of the required substrings
    static int countSubStr(String str, int len)
    {
        // To store the final answer
        int ans = 0;
     
        // Loop to find the answer
        for (int i = 0; i < len; i++)
        {
     
            // Condition to update the answer
            if (str.charAt(i) == '0')
                ans += (i + 1);
        }
        return ans;
    }
     
    // Driver code
    public static void main (String[] args)
    {
        String str = "10010";
        int len = str.length();
     
        System.out.println(countSubStr(str, len));
    }
}
 
// This code is contributed by AnkitRai01


Python3
# Python3 implementation of the approach
 
# Function to return the count
# of the required substrrings
def countSubStr(strr, lenn):
     
    # To store the final answer
    ans = 0
 
    # Loop to find the answer
    for i in range(lenn):
 
        # Condition to update the answer
        if (strr[i] == '0'):
            ans += (i + 1)
 
    return ans
 
# Driver code
strr = "10010"
lenn = len(strr)
 
print(countSubStr(strr, lenn))
 
# This code is contributed by Mohit Kumar


C#
// C# implementation of the approach
using System;
 
class GFG
{
     
    // Function to return the count
    // of the required substrings
    static int countSubStr(string str, int len)
    {
        // To store the final answer
        int ans = 0;
     
        // Loop to find the answer
        for (int i = 0; i < len; i++)
        {
     
            // Condition to update the answer
            if (str[i] == '0')
                ans += (i + 1);
        }
        return ans;
    }
     
    // Driver code
    public static void Main ()
    {
        string str = "10010";
        int len = str.Length;
     
        Console.WriteLine(countSubStr(str, len));
    }
}
 
// This code is contributed by AnkitRai01


输出:
10

时间复杂度: O(N),N =字符串长度

辅助空间: O(1)