1. 程式人生 > 其它 >第十八章 Tagging_Redis-6.2.1 伺服器部署

第十八章 Tagging_Redis-6.2.1 伺服器部署

已有方法rand7可生成 1 到 7 範圍內的均勻隨機整數,試寫一個方法rand10生成 1 到 10 範圍內的均勻隨機整數。

不要使用系統的Math.random()方法。

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/implement-rand10-using-rand7
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

import java.util.Random;
import java.util.Scanner;

/**
 * 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 {

    private int rand40() {
        int num = 0;
        do {
            // 0 1 2 3 4 5 6
            // 0 7 14 21 28 35 42
            num = (rand7() - 1) * 7 + rand7() - 1;
        } while (num > 39);
        return num + 1;
    }

    public int rand10() {
        return rand40() % 10 + 1;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            int n = in.nextInt();
            Solution solution = new Solution();
            while (n-- > 0) {
                System.out.println(solution.rand10());
            }
        }
    }
}

abstract class SolBase {
    public int rand7() {
        return new Random().nextInt(7) + 1;
    }
}
心之所向,素履以往 生如逆旅,一葦以航