b******y 发帖数: 9224 | 1 jdk里面的源程序如下:
public int nextInt(int n) {
if (n<=0)
throw new IllegalArgumentException("n must be positive");
if ((n & -n) == n) // i.e., n is a power of 2
return (int)((n * (long)next(31)) >> 31);
int bits, val;
do {
bits = next(31);
val = bits % n;
} while(bits - val + (n-1) < 0);
return val;
}
读不懂的地方是while(bits - val + (n-1) < 0);
为啥要这样判断呢? | c*****t 发帖数: 1879 | 2 javadoc 里面写着呢:
*
* The loop at the bottom only accepts a value, if the random
* number was between 0 and the highest number less then 1<<31,
* which is divisible by n. The probability for this is high for small
* n, and the worst case is 1/2 (for n=(1<<30)+1).
*
【在 b******y 的大作中提到】 : jdk里面的源程序如下: : public int nextInt(int n) { : if (n<=0) : throw new IllegalArgumentException("n must be positive"); : if ((n & -n) == n) // i.e., n is a power of 2 : return (int)((n * (long)next(31)) >> 31); : int bits, val; : do { : bits = next(31); : val = bits % n;
|
|