feat: 470_implement_rand10_using_rand7

This commit is contained in:
SquidSpirit 2025-09-23 01:37:05 +08:00
parent ba7ae5f04c
commit 480314c01e
3 changed files with 37 additions and 0 deletions

View File

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "implement_rand10_using_rand7"
version = "0.1.0"

View File

@ -0,0 +1,6 @@
[package]
name = "implement_rand10_using_rand7"
version = "0.1.0"
edition = "2024"
[dependencies]

View File

@ -0,0 +1,24 @@
#[inline]
fn rand7() -> i32 {
(std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
% 7) as i32
}
pub struct Solution;
impl Solution {
pub fn rand10() -> i32 {
let mut rnd: i32;
loop {
rnd = (rand7() - 1) * 7 + rand7(); // [1, 49]
if rnd <= 40 {
break;
}
}
rnd % 10 + 1
}
}