)(Rand7を使用してRand10()を実装

機能所与  rand7 1~7の範囲で一様乱数整数を生成し、機能書く  rand10 10の範囲1において一様乱数整数を生成します。

システムの使用しないでください  Math.random()

例1:

入力: 1
 出力: [7]

考える:数学を、10を与えるために9 + 1 0〜1〜を与えるために、1-7 0-48に変換することができ、及び0-40は、10を法があり、

  1. ゼロベース  random7:  random7-1(0..6)
  2. 拡大するゼロベースの  random7 ゼロベースに  random49: (random7-1)*7 + (random7-1)
  3. 再び圧延によって40の上に番号を破棄し、我々はゼロベースを取得します  random40
    while(random40>=40){
    	random40 = (random7-1)*7 + (random7-1)
    }
    
  4. 折りたたみゼロをベース  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;
    }
}

 

公開された673元の記事 ウォン称賛13 ビュー180 000 +

おすすめ

転載: blog.csdn.net/u013325815/article/details/105194408