LeetCode 470. Implement Rand10()

2019-03-24  本文已影响0人  cb_guo

题目描述

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.
Do NOT use system's Math.random().

Example 1:

Input: 1
Output: [7]

Example 2:

Input: 2
Output: [8,4]

Example 3:

Input: 3
Output: [8,1,10]

题目思路

代码 C++

// 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 result = 7 * (rand7() - 1) + rand7();
        while(result > 40){
            result = 7 * (rand7() - 1) + rand7();
        }
        return result%10 + 1;
    }
};

总结展望

上一篇 下一篇

猜你喜欢

热点阅读