Reverse a number in rust

how to reverse a number like 123 to 321

That's not a normal numerical operation per se, so instead I'll show it using a String:

let my_str: String = format!("{:?}", 123);
let reversed = my_str.chars().rev().collect::<String>();
println!("{}", reversed);

Playground
If you want to turn it into a number again:

let my_num: usize = reversed.parse().unwrap();

Playground.

2 Likes

If you want to avoid going through a String, here is a relatively simple way:

let radix = 10;
let mut n = 123;
let mut reversed = 0;

while n != 0 {
    reversed = reversed * radix + n % radix;
    n /= radix;
}

assert_eq!(reversed, 321);

playground

Since this is something that kept coming up for online puzzles, I created a simple crate (radixal) to add these kinds of methods to unsigned integers to make my life easier.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.