📌  相关文章
📜  给定长度的二进制字符串的数量至少由1组成

📅  最后修改于: 2021-04-29 13:36:05             🧑  作者: Mango

给定整数N ,任务是打印长度为N的二进制字符串的数目,该数目至少为1。

例子:

方法:
我们可以观察到:

请按照以下步骤解决问题:

  • 初始化X = 1。
  • 通过对X执行N-1次按位左移运算,最多可计算2N
  • 最后,打印X – 1作为必需答案。

下面是我们方法的实现:

C++
// C++ Program to implement
// the above approach
#include 
using namespace std;
  
// Function to return
// the count of strings
long count_strings(long n)
{
    int x = 1;
  
    // Calculate pow(2, n)
    for (int i = 1; i < n; i++) {
        x = (1 << x);
    }
  
    // Return pow(2, n) - 1
    return x - 1;
}
  
// Driver Code
int main()
{
    long n = 3;
  
    cout << count_strings(n);
  
    return 0;
}


Java
// Java program to implement
// the above approach
import java.util.*;
  
class GFG{
  
// Function to return
// the count of Strings
static long count_Strings(long n)
{
    int x = 1;
  
    // Calculate Math.pow(2, n)
    for(int i = 1; i < n; i++)
    {
       x = (1 << x);
    }
  
    // Return Math.pow(2, n) - 1
    return x - 1;
}
  
// Driver Code
public static void main(String[] args)
{
    long n = 3;
  
    System.out.print(count_Strings(n));
}
}
  
// This code is contributed by Amit Katiyar


Python3
# Python3 program to implement
# the above approach
  
# Function to return
# the count of Strings
def count_Strings(n):
      
    x = 1;
  
    # Calculate pow(2, n)
    for i in range(1, n):
        x = (1 << x);
  
    # Return pow(2, n) - 1
    return x - 1;
  
# Driver Code
if __name__ == '__main__':
      
    n = 3;
  
    print(count_Strings(n));
  
# This code is contributed by Princi Singh


C#
// C# program to implement
// the above approach
using System;
  
class GFG{
  
// Function to return
// the count of Strings
static long count_Strings(long n)
{
    int x = 1;
  
    // Calculate Math.Pow(2, n)
    for(int i = 1; i < n; i++)
    {
       x = (1 << x);
    }
      
    // Return Math.Pow(2, n) - 1
    return x - 1;
}
  
// Driver Code
public static void Main(String[] args)
{
    long n = 3;
  
    Console.Write(count_Strings(n));
}
}
  
// This code is contributed by Amit Katiyar


输出:
3


时间复杂度: O(N)
辅助空间: O(1)