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

📅  最后修改于: 2021-04-17 15:13:34             🧑  作者: 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


输出:
0101101

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