1. 程式人生 > >[leetcode]470. Implement Rand10() Using Rand7()

[leetcode]470. Implement Rand10() Using Rand7()

[leetcode]470. Implement Rand10() Using Rand7()


Analysis

今天被微博上的孫藝興bot笑死,哈哈哈哈哈—— [每天刷題並不難0.0]

Given a function rand7 which generates a uniform random integer in the range 1 to 7, write a function rand10 which generates a uniform random integer in the range 1 to 10.
在這裡插入圖片描述
利用rand7()生成一個randM() (此處M是10的整數)

Implement

// 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 = rand40();
        return num%10+1;
    }
private:
    int rand49(){
        int num = 7*(rand7()-1)+rand7()-1;
        return
num; } int rand40(){ int num = rand49(); while(num >= 40) num = rand49(); return num; } };