From df1fa87bb3babf74b4a319287d550b620c63ca3d Mon Sep 17 00:00:00 2001 From: Bauke Date: Wed, 6 Apr 2022 14:31:17 +0200 Subject: [PATCH] Solve reverse-integer. --- source/lib.rs | 1 + source/reverse_integer/mod.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 source/reverse_integer/mod.rs diff --git a/source/lib.rs b/source/lib.rs index 40aceb0..9823fe9 100644 --- a/source/lib.rs +++ b/source/lib.rs @@ -1 +1,2 @@ +pub mod reverse_integer; pub mod two_sum; diff --git a/source/reverse_integer/mod.rs b/source/reverse_integer/mod.rs new file mode 100644 index 0000000..72aaf47 --- /dev/null +++ b/source/reverse_integer/mod.rs @@ -0,0 +1,26 @@ +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::() + // 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() +} + +#[test] +fn test_reverse_integer() { + assert_eq!(reverse(123), 321); + assert_eq!(reverse(-123), -321); + assert_eq!(reverse(120), 21); + assert_eq!(reverse(i32::MAX), 0); + assert_eq!(reverse(i32::MIN), 0); +}