Golang | Leetcode Golang题解之第470题用Rand7()实现Rand10()

题目:

Golang | Leetcode Golang题解之第470题用Rand7()实现Rand10()

题解:

func rand10() int {
    for {
        a := rand7()
        b := rand7()
        idx := (a-1)*7 + b
        if idx <= 40 {
            return 1 + (idx-1)%10
        }
        a = idx - 40
        b = rand7()
        // get uniform dist from 1 - 63
        idx = (a-1)*7 + b
        if idx <= 60 {
            return 1 + (idx-1)%10
        }
        a = idx - 60
        b = rand7()
        // get uniform dist from 1 - 21
        idx = (a-1)*7 + b
        if idx <= 20 {
            return 1 + (idx-1)%10
        }
    }
}
版权声明:如无特殊标注,文章均来自网络,本站编辑整理,转载时请以链接形式注明文章出处,请自行分辨。

本文链接:https://www.shbk5.com/dnsj/72832.html