Skip to content

470. Implement Rand10() Using Rand7()

  • Time: $O(1)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// The rand7() API is already defined for you.
// int rand7();
// @return a random integer in the range 1 to 7

class Solution {
 public:
  int rand10() {
    int num = 40;

    while (num >= 40)
      num = (rand7() - 1) * 7 + rand7() - 1;

    return num % 10 + 1;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
/**
 * 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 {
  public int rand10() {
    int num = 40;

    while (num >= 40)
      num = (rand7() - 1) * 7 + rand7() - 1;

    return num % 10 + 1;
  }
}