Rust program to reverse a number using recursion

Rust | Reverse Number Example: Given a number, we have to reverse the number using recursion.
Submitted by Nidhi, on October 11, 2021

Problem Solution:

In this program, we will create a recursive function to return the reverse number of a given number to the calling function.

Program/Source Code:

The source code to reverse a number using recursion is given below. The given program is compiled and executed successfully.

// Rust program to reverse a number 
// using recursion

fn reverse(num:i32, len:u32)->i32{
    let x:i32 = 10;
    if len == 1{
        return num;
    }
    else{
        return (num % 10) * x.pow(len - 1) + reverse(num / 10, len-1);
    }
}

fn main() {
    let rs = reverse(1234,4);
    
    println!("Reversed number: {}", rs);
}

Output:

Reversed number: 4321

Explanation:

In the above program, we created two functions reverse() and main(). The reverse() function is a recursive function, which is used to return the reverse of a given number to the calling function.

In the main() function, we called the reverse() function and printed the result.

Rust Functions Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.