Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Integer to Binary String in Python
Next article icon

Given a number n, the task is to generate a random binary string of length n.
Examples: 

Input: 7Output: Desired length of random binary string is:  1000001Input: 5Output: Desired length of random binary string is:  01001


Approach

Below is the implementation.

Python3
# Python program for random# binary string generationimportrandom# Function to create the# random binary stringdefrand_key(p):# Variable to store the# stringkey1=""# Loop to find the string# of desired lengthforiinrange(p):# randint function to generate# 0, 1 randomly and converting# the result into strtemp=str(random.randint(0,1))# Concatenation the random 0, 1# to the final resultkey1+=tempreturn(key1)# Driver Coden=7str1=rand_key(n)print("Desired length random binary string is: ",str1)

Output:

Desired length random binary string is:  1000001

The Time and Space Complexity for all the methods are the same:

Time Complexity:O(n)

Auxiliary Space:O(n)

Using random.getrandbits():

Python3
importrandomdefgenerate_binary_string(n):# Generate a random number with n bitsnumber=random.getrandbits(n)# Convert the number to binarybinary_string=format(number,'0b')returnbinary_string# Test the functionn=7print("Random binary string of length{}:{}".format(n,generate_binary_string(n)))#This code is contributed by Edula Vinay Kumar Reddy

Output
Random binary string of length 7: 1010000

Explanation:

The random.getrandbits(n) function generates a random number with n bits.
The format() function is used to convert the number to binary format. The format string '0b' specifies that the output should be in binary form.
 

Time Complexity: O(n), where n is the number of bits in the binary string.

Auxiliary Space: O(n), where n is the number of bits in the binary string. This is the space required to store the binary string.


Improve

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp