gpt4 book ai didi

java - 如何在 Java 中创建显示为二进制值的范围内的随机数?

转载 作者:行者123 更新时间:2023-11-29 10:01:28 25 4
gpt4 key购买 nike

我可以使用 Random 方法生成随机数。但我想创建以二进制格式显示的随机数。数字必须在特定范围内。

Random numbers should be between 5 and 10 digits, inclusive.

例如:011110、0111100、010110101。

最佳答案

尝试以下代码片段(从 This Stack Overflow question 生成随机数)

import java.util.Random;

public class Main {
private static Random random = new Random();
private static final int MAX = 1023;
private static final int MIN = 16;

public static void main(String[] args) {
Integer randInt = random.nextInt((MAX - MIN) + 1) + MIN;
System.out.println("random binary is: " + Integer.toBinaryString(randInt));
}
}

MIN of 16 强制执行最少 5 个二进制数字,其中:

10000 is equal to 16

MAX of 1023 强制最多 10 个二进制数字,其中:

111111111 equal to 1023

Utility 方法 Integer.toBinaryString(int)Integer 转换为二进制可读格式(强制执行唯一的“1”和“0”条件)

关于java - 如何在 Java 中创建显示为二进制值的范围内的随机数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25668144/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com