How to write a recursive function that counts digits of a number in Rust

1 Answer

0 votes
fn count_digits(number: i32) -> i32 {
    // Base case: If the number is 0, return 0
    if number == 0 {
        return 0;
    }

    // Recursive case: Divide the number by 10 and count recursively
    1 + count_digits(number / 10)
}

fn main() {
    let num = 89031;
    
    println!("Number of digits in {} is: {}", num, count_digits(num)); 
}


 
       
/*
run:
 
Number of digits in 89031 is: 5
      
*/

 



answered Apr 8, 2025 by avibootz
...