機能所与 rand7
1~7の範囲で一様乱数整数を生成し、機能書く rand10
10の範囲1において一様乱数整数を生成します。
システムの使用しないでください Math.random()
。
例1:
入力: 1 出力: [7]
考える:数学を、10を与えるために9 + 1 0〜1〜を与えるために、1-7 0-48に変換することができ、及び0-40は、10を法があり、
- ゼロベース
random7
:random7-1
(0..6) - 拡大するゼロベースの
random7
ゼロベースにrandom49
:(random7-1)*7 + (random7-1)
- 再び圧延によって40の上に番号を破棄し、我々はゼロベースを取得します
random40
:while(random40>=40){ random40 = (random7-1)*7 + (random7-1) }
- 折りたたみゼロをベース
random40
に1ベースrandom10
random10 = random40%10+1
/**
* The rand7() API is already defined in the parent class SolBase.
* public int rand7();
* @return a random integer in the range 1 to 7
*/
class Solution extends SolBase {
public int rand10() {
int rand40 = Integer.MAX_VALUE;
while(rand40 >= 40) {
rand40 = (rand7() - 1) * 7 + (rand7() - 1);
}
return rand40 % 10 + 1;
}
}