【Leetcode】470. 用 Rand7() 实现 Rand10()

题目描述

在这里插入图片描述

// 470. 用 Rand7() 实现 Rand10()

// 已有方法 rand7 可生成 1 到 7 范围内的均匀随机整数,试写一个方法 rand10 生成
// 1 到 10 范围内的均匀随机整数。

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


题解

/**
 * The rand7() API is already defined in the parent class SolBase.
 * public int rand7();
 * @return a random integer in the range 1 to 7
 */



// 弄不懂,我也是直接看答案的,推荐这篇:
// https://leetcode-cn.com/problems/implement-rand10-using-rand7/solution/cong-zui-ji-chu-de-jiang-qi-ru-he-zuo-dao-jun-yun-/
// 第二个a=num-40为rand9(),第二个num为rand63(),
// 第三个a= num - 60为rand3(),第三个num为rand21()
// 
// 执行用时:7 ms, 在所有 Java 提交中击败了99.34%的用户
// 内存消耗:43.6 MB, 在所有 Java 提交中击败了32.92%的用户
class Solution extends SolBase {
    public int rand10() {
        while (true) {
			int num = (rand7() - 1) * 7 + rand7();
			if (num <= 40) return num % 10 + 1;
		}
    }
}



// 第二个a=num-40为rand9(),第二个num为rand63(),
// 第三个a= num - 60为rand3(),第三个num为rand21()
//
// 执行用时:7 ms, 在所有 Java 提交中击败了99.34%的用户
// 内存消耗:43.7 MB, 在所有 Java 提交中击败了24.28%的用户
class Solution extends SolBase {
    public int rand10() {
        while (true) {
			int a = rand7();
			int b = rand7();
			int num = (a - 1)*7 + b;
			if (num <= 40) return num % 10 + 1;
			
			a = num - 40;
			b = rand7();
			num = (a - 1)*7 + b;
			if (num <= 60) return num % 10 + 1;
			
			a = num - 60;
			b = rand7();
			num = (a - 1)*7 + b;
			if (num <= 20) return num % 10 + 1;
		}
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

锥栗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值