1
Fork 0
leetcode/source/reverse_integer/mod.rs

18 lines
550 B
Rust
Raw Permalink Normal View History

2022-04-06 12:31:17 +00:00
pub fn reverse(number: i32) -> i32 {
number
// Convert to an absolute number without wrapping or panicking.
.unsigned_abs()
// Convert the number to string, then reverse all its characters.
.to_string()
.chars()
.rev()
// Collect the reversed characters back into a string.
.collect::<String>()
// Parse the string into an i32.
.parse()
// If it returns an Err then use 0 instead.
.unwrap_or(0)
// Then multiply by 0, 1 or -1 depending on the sign of the original number.
* number.signum()
}