给定长度为N 的二进制字符串str ,任务是找到str的可被2整除的子序列的计数。子序列中允许有前导零。
例子:
Input: str = “101”
Output: 2
“0” and “10” are the only subsequences
which are divisible by 2.
Input: str = “10010”
Output: 22
朴素的方法:朴素的方法是生成所有可能的子序列并检查它们是否可以被 2 整除。这样做的时间复杂度为 O(2 N * N)。
有效的方法:可以观察到,任何二进制数只有以0结尾才能被2整除。现在,任务只是计算以0结尾的子序列的数量。因此,对于每个索引i使得str[i] = ‘0’ ,找到以i结尾的子序列的数量。该值等于2 i (基于 0 的索引)。因此,最终答案将等于所有i的2 i的总和,使得str[i] = ‘0’ 。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the count
// of the required subsequences
int countSubSeq(string str, int len)
{
// To store the final answer
int ans = 0;
// Multiplier
int mul = 1;
// Loop to find the answer
for (int i = 0; i < len; i++) {
// Condition to update the answer
if (str[i] == '0')
ans += mul;
// updating multiplier
mul *= 2;
}
return ans;
}
// Driver code
int main()
{
string str = "10010";
int len = str.length();
cout << countSubSeq(str, len);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
// Function to return the count
// of the required subsequences
static int countSubSeq(String str, int len)
{
// To store the final answer
int ans = 0;
// Multiplier
int mul = 1;
// Loop to find the answer
for (int i = 0; i < len; i++)
{
// Condition to update the answer
if (str.charAt(i) == '0')
ans += mul;
// updating multiplier
mul *= 2;
}
return ans;
}
// Driver code
public static void main(String[] args)
{
String str = "10010";
int len = str.length();
System.out.print(countSubSeq(str, len));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 implementation of the approach
# Function to return the count
# of the required subsequences
def countSubSeq(strr, lenn):
# To store the final answer
ans = 0
# Multiplier
mul = 1
# Loop to find the answer
for i in range(lenn):
# Condition to update the answer
if (strr[i] == '0'):
ans += mul
# updating multiplier
mul *= 2
return ans
# Driver code
strr = "10010"
lenn = len(strr)
print(countSubSeq(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 subsequences
static int countSubSeq(string str, int len)
{
// To store the final answer
int ans = 0;
// Multiplier
int mul = 1;
// Loop to find the answer
for (int i = 0; i < len; i++)
{
// Condition to update the answer
if (str[i] == '0')
ans += mul;
// updating multiplier
mul *= 2;
}
return ans;
}
// Driver code
static public void Main ()
{
string str = "10010";
int len = str.Length;
Console.WriteLine(countSubSeq(str, len));
}
}
// This code is contributed by AnkitRai01
Javascript
输出:
22
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。