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,845 questions

51,766 answers

573 users

How to convert a vector of digits to an integer add 1 and convert it back to a vector of digits in Rust

1 Answer

0 votes
fn convert_vector_of_digits_to_int(digits: &[u32]) -> u32 {
    let mut n = 0;
    for &digit in digits {
        n = n * 10 + digit;
    }
    n
}

fn convert_int_to_vector_of_digits(digits: &mut Vec<u32>, mut n: u32) {
    let len = digits.len();
    let mut i = len - 1;

    while n > 0 {
        digits[i] = n % 10; // Extract last digit
        n /= 10;           // Remove the last digit
        if i > 0 {         // Prevent out-of-bound access
            i -= 1;
        }
    }
}

fn main() {
    // Initial vector of digits
    let mut v = vec![9, 4, 6, 9];

    // Convert vector of digits to an integer
    let mut n = convert_vector_of_digits_to_int(&v);

    // Increment the integer
    n += 1;

    // Convert the incremented integer back to an vector of digits
    convert_int_to_vector_of_digits(&mut v, n);

    // Print the results
    println!("n = {}", n);
    println!("{:?}", v);
}



/*
run:

n = 9470
[9, 4, 7, 0]

*/

 



answered Apr 12, 2025 by avibootz
edited Apr 12, 2025 by avibootz
...