diff --git a/src/solution/mod.rs b/src/solution/mod.rs index 4abad37..4bc0247 100644 --- a/src/solution/mod.rs +++ b/src/solution/mod.rs @@ -10,3 +10,4 @@ mod s0052_n_queens_ii; mod s0912_sort_an_array; mod s1276_number_of_burgers_with_no_waste_of_ingredients; mod s0006_zigzag_conversion; +mod s0007_reverse_integer; diff --git a/src/solution/s0007_reverse_integer.rs b/src/solution/s0007_reverse_integer.rs new file mode 100644 index 0000000..13d9b6f --- /dev/null +++ b/src/solution/s0007_reverse_integer.rs @@ -0,0 +1,66 @@ +/** + * [7] Reverse Integer + * + * Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1], then return 0. + * Assume the environment does not allow you to store 64-bit integers (signed or unsigned). + * + * Example 1: + * + * Input: x = 123 + * Output: 321 + * + * Example 2: + * + * Input: x = -123 + * Output: -321 + * + * Example 3: + * + * Input: x = 120 + * Output: 21 + * + * + * Constraints: + * + * -2^31 <= x <= 2^31 - 1 + * + */ +pub struct Solution {} + +// problem: https://leetcode.cn/problems/reverse-integer/ +// discuss: https://leetcode.cn/problems/reverse-integer/discuss/?currentPage=1&orderBy=most_votes&query= + +// submission codes start here + +impl Solution { + pub fn reverse(x: i32) -> i32 { + let (num, negative) = if x < 0 { + (-x, true) + } else { + (x, false) + }; + + let str = num.to_string(); + let mut str: String = str.chars().rev().collect(); + if negative { + str.insert(0, '-'); + } + + str.parse::().unwrap_or_else(|_| 0) + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_7() { + assert_eq!(321, Solution::reverse(123)); + assert_eq!(-321, Solution::reverse(-123)); + assert_eq!(21, Solution::reverse(120)); + assert_eq!(0, Solution::reverse(0)); + } +}