How to extract the last N digits from a number in Rust

1 Answer

0 votes
/*
    Extracts the last N digits from a given number.

    Approach:
      - To get the last N digits, compute: number % (10^digits)
      - This avoids string manipulation and uses efficient arithmetic.

    Parameters:
      number : the original integer
      digits : how many digits to extract from the end

    Returns:
      The last N digits as an integer.
*/
fn get_last_n_digits(number: u64, digits: u32) -> u64 {
    // Compute 10^digits using u64::pow
    let divisor: u64 = 10u64.pow(digits);

    // Modulo returns the remainder, which is exactly the last N digits
    number % divisor
}

fn main() {
    // Example values
    let number: u64 = 987_654_321;
    let digits: u32 = 4;

    // Extract the last N digits
    let result: u64 = get_last_n_digits(number, digits);

    // Display the result
    println!("Original number: {}", number);
    println!("Digits requested: {}", digits);
    println!("Last {} digits: {}", digits, result);
}


/*
run:

Original number: 987654321
Digits requested: 4
Last 4 digits: 4321

*/

 



answered Sep 18 by avibootz
...