1
Fork 0

Solve reverse-integer.

This commit is contained in:
Bauke 2022-04-06 14:31:17 +02:00
parent a651f9ed80
commit df1fa87bb3
Signed by: Bauke
GPG Key ID: C1C0F29952BCF558
2 changed files with 27 additions and 0 deletions

View File

@ -1 +1,2 @@
pub mod reverse_integer;
pub mod two_sum; pub mod two_sum;

View File

@ -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::<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()
}
#[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);
}