Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,907 questions

51,839 answers

573 users

How to get the first x leftmost digits of an integer number in Rust

1 Answer

0 votes
use rand::Rng;

fn x_leftmost_digit(mut n: u32, x: u32) -> u32 {
    let x = 10u32.pow(x);
    while n > x {
        n /= 10;
    }
    n
}

fn main() {
    let mut rng = rand::thread_rng();
    for _i in 1..=5 {
        let n = rng.gen_range(1..=100000);
        let x = rng.gen_range(1..=5);
        println!("{} leftmost digit of {} is {}", x, n, x_leftmost_digit(n, x));
    }
}


   
/*
run:
  
2 leftmost digit of 23606 is 23
4 leftmost digit of 95180 is 9518
3 leftmost digit of 58205 is 582
2 leftmost digit of 9273 is 92
5 leftmost digit of 56048 is 56048
  
*/

 



answered Dec 8, 2024 by avibootz
...