📜  生成长度为 N 的随机二进制字符串

📅  最后修改于: 2021-09-06 11:28:18             🧑  作者: Mango

给定一个正整数N ,任务是生成一个长度为N的随机二进制字符串。

例子:

方法:给定的问题可以通过使用 rand()函数来解决,该函数在[0, RAND_MAX ]范围内生成一个随机数并借助该函数返回的值,在任何范围[L, R]内的任何数字可以生成为(rand() % (R – L + 1)) + L 。请按照以下步骤解决问题:

  • 初始化一个空字符串,比如说S。
  • 迭代范围[0, N – 1]并执行以下步骤:
    • 使用 rand()函数在 [0, 1] 范围内存储一个随机数。
    • 将随机生成的01附加到字符串S的末尾。
  • 完成上述步骤后,将字符串S打印为结果二进制字符串。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find a random
// number between 0 or 1
int findRandom()
{
    // Generate the random number
    int num = ((int)rand() % 2);
 
    // Return the generated number
    return num;
}
 
// Function to generate a random
// binary string of length N
void generateBinaryString(int N)
{
    srand(time(NULL));
 
    // Stores the empty string
    string S = "";
 
    // Iterate over the range [0, N - 1]
    for (int i = 0; i < N; i++) {
 
        // Store the random number
        int x = findRandom();
 
        // Append it to the string
        S += to_string(x);
    }
 
    // Print the resulting string
    cout << S;
}
 
// Driver Code
int main()
{
    int N = 7;
    generateBinaryString(N);
 
    return 0;
}


Java
// Java program for the above approach
class GFG{
     
// Function to find a random
// number between 0 or 1
static int findRandom()
{
     
    // Generate the random number
    int num = (1 + (int)(Math.random() * 100)) % 2;
 
    // Return the generated number
    return num;
}
 
// Function to generate a random
// binary string of length N
static void generateBinaryString(int N)
{
     
    // Stores the empty string
    String S = "";
 
    // Iterate over the range [0, N - 1]
    for(int i = 0; i < N; i++)
    {
         
        // Store the random number
        int x = findRandom();
 
        // Append it to the string
        S = S + String.valueOf(x);
    }
 
    // Print the resulting string
    System.out.println(S);
}
 
// Driver Code
public static void main (String[] args)
{
    int N = 7;
     
    generateBinaryString(N);
}
}
 
// This code is contributed by AnkThon


Python3
# Python3 program for the above approach
import random
 
# Function to find a random
# number between 0 or 1
def findRandom():
     
    # Generate the random number
    num = random.randint(0, 1)
 
    # Return the generated number
    return num
 
# Function to generate a random
# binary string of length N
def generateBinaryString(N):
     
    # Stores the empty string
    S = ""
 
    # Iterate over the range [0, N - 1]
    for i in range(N):
         
        # Store the random number
        x = findRandom()
 
        # Append it to the string
        S += str(x)
     
    # Print the resulting string
    print(S)
 
# Driver Code
N = 7
 
generateBinaryString(N)
 
# This code is contributed by sanjoy_62


Javascript


输出:
0101101

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

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live