p144 rand10()をrand7()で実装(leetcode 470)

1:問題の解決策

x> yの場合、randxを使用してrandyを実装する必要があります。このうち、randxは、1からxを等しい確率で生成する関数を表します。randyは、1からyを生成する等確率関数を表します。

2:完全なコード例(C ++バージョンとJavaバージョン)

C ++:

クラスSolution {
 public int rand10()
    { 
        int x = 2147483647 ;
        while(x> 10 
            x = 7 *(rand7()- 1)+ rand7();
        xを返します。
    } 
};

Java:

クラスSolutionはSolBaseを拡張します{
         public  int rand10()
        { 
              int x = Integer.MAX_VALUE;
              while(x> 10 
                  x = 7 *(rand7()- 1)+ rand7(); 
              
              xを返します。
        } 
    }

 

おすすめ

転載: www.cnblogs.com/repinkply/p/12727954.html