有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java生成30到32位之间的随机数

在阅读其他文章时,我想我必须使用BigInteger生成20000个介于30到32位之间的随机数

public BigInteger(int numBits, Random rnd)

但这不允许数字的最小和最大范围

谢谢


共 (1) 个答案

  1. # 1 楼答案

    如果你想使用这个功能,你可以

    public static BigInteger random(Random rand, BigInteger minValue, BigInteger maxValue) {
        BigInteger range = maxValue.subtract(minValue).add(BigInteger.ONE);
        int bits = range.bitLength();
        BigInteger ret;
        do {
            ret = new BigInteger(bits, rand);
        } while(ret.compareTo(range) >= 0);
        return ret.add(minValue);
    }