Algorithm to Reverse Integer

pub fn reverse (mut I:u32) -> u32 {
let mut out:f32 = 0;

while I != 0 {
out=out * 10 + I % 10;
I=I/10

}

return out as u32;

Hello Rustaceans, I'm trying to implement reverse integer algorithm in rust but before I return out, I will like to do something like this :

if(out> Integer.MAX_VALUE || out < Integer. MIN_VALUE) return 0

The above is a Java implementation before returning the out.
Thanks a lot

The simplest way is probably to calculate in u64 and try to convert back at the end:

pub fn reverse(mut i: u32) -> u32 {
    let mut out: u64 = 0;
    while i != 0 {
        out = out * 10 + (i % 10) as u64;
        i /= 10;
    }
    
    out.try_into().unwrap_or(0)
}
2 Likes

Noted
Thanks

An alternative approach is to round-trip through a string representation, which perhaps reflects the underlying intent better (at a cost of heap allocations):

pub fn reverse(i: u32) -> u32 {
    format!("{i}").chars().rev().collect::<String>().parse().unwrap_or(0)
}
3 Likes

Noted thanks. I guess this method will impact the runtime complexity since it's allocated memory on the heap.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.