20231231 Finished

This commit is contained in:
jackfiled 2023-12-31 11:44:31 +08:00
parent 602667bfee
commit a4f5f284b8
2 changed files with 67 additions and 0 deletions

View File

@ -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;

View File

@ -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).
*
* <strong class="example">Example 1:
*
* Input: x = 123
* Output: 321
*
* <strong class="example">Example 2:
*
* Input: x = -123
* Output: -321
*
* <strong class="example">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::<i32>().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));
}
}