ADVERTISEMENT
ADVERTISEMENT

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 »



ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.