Skip to content

The rand7() API is already defined in the parent class SolBase. public int rand7(); @return a random integer in the range 1 to 7

java
/*
 * @lc app=leetcode.cn id=470 lang=java
 *
 * [470] 用 Rand7() 实现 Rand10()
 */

// @lc code=start
/**
 * 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 {
    /**
     * (randX() - 1) * Y + randX() = randX*Y()
     * 通过这个算式计算出来rand49, 然后取到了41-49就重复取
     */
    public int rand10() {
        int rand49;
        while (true) {
            rand49 = (rand7() - 1) * 7 + rand7();
            if (rand49 <= 40) return rand49 % 10 + 1;
            int rand63 = (rand49 - 40 - 1) * 7 + rand7();
            if (rand63 <= 60) return rand63 % 10 + 1;
            int rand21 = (rand63 - 60 - 1) * 7 + rand7();
            if (rand21 <= 20) return rand21 % 10 + 1;
        }
    }
}
// @lc code=end

Personal Knowledge Base