返回轨道
算法 · 2026-05-14 · 19 阅读

P140 用 rand7() 实现 rand10()

算法 19 阅读

信号摘要

难度:Medium · 时长:06:43 · leetcode 470

P140 用 rand7() 实现 rand10()

未对外公开播放权限
点击查看说明

描述

这个题目说的是,给你一个函数 rand7(),它能等概率地生成 1~7 之间的随机数,你要用它实现 rand10(),这个函数可以等概率地生成 1~10 之间的随机数。

代码

public class AlgoCasts {

  private final Random RANDOM = new Random();

  // generate integer in the range 1 to 7
  private int rand7() {
    return RANDOM.nextInt(7) + 1;
  }

  public int rand10() {
    int x = Integer.MAX_VALUE;
    while (x > 10)
      x = 7 * (rand7() - 1) + rand7();
    return x;
  }

  public int rand10Opt() {
    int x = Integer.MAX_VALUE;
    while (x > 40)
      x = 7 * (rand7() - 1) + rand7();
    return x % 10 + 1;
  }

}

📡 通讯频道