File tree 3 files changed +82
-1
lines changed
3 files changed +82
-1
lines changed Original file line number Diff line number Diff line change 1
- mod p0004_median_of_two_sorted_arrays;
1
+ mod p0004_median_of_two_sorted_arrays; mod p0007_reverse_integer ;
Original file line number Diff line number Diff line change @@ -3,3 +3,4 @@ mod s0002_add_two_numbers;
3
3
mod s0003_longest_substring_without_repeating_characters;
4
4
mod s0005_longest_palindromic_substring;
5
5
mod s0006_zigzag_conversion;
6
+ mod s0007_reverse_integer;
Original file line number Diff line number Diff line change
1
+ /**
2
+ * [7] 整数反转
3
+ *
4
+ * 给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。
5
+ * 如果反转后整数超过 32 位的有符号整数的范围 [−2^31, 2^31 − 1] ,就返回 0。
6
+ * 假设环境不允许存储 64 位整数(有符号或无符号)。
7
+ *
8
+ * 示例 1:
9
+ *
10
+ * 输入:x = 123
11
+ * 输出:321
12
+ *
13
+ * 示例 2:
14
+ *
15
+ * 输入:x = -123
16
+ * 输出:-321
17
+ *
18
+ * 示例 3:
19
+ *
20
+ * 输入:x = 120
21
+ * 输出:21
22
+ *
23
+ * 示例 4:
24
+ *
25
+ * 输入:x = 0
26
+ * 输出:0
27
+ *
28
+ *
29
+ * 提示:
30
+ *
31
+ * -2^31 <= x <= 2^31 - 1
32
+ *
33
+ */
34
+ pub struct Solution { }
35
+
36
+ // problem: https://leetcode.cn/problems/reverse-integer/
37
+ // discuss: https://leetcode.cn/problems/reverse-integer/discuss/?currentPage=1&orderBy=most_votes&query=
38
+
39
+ // submission codes start here
40
+
41
+ impl Solution {
42
+ pub fn reverse ( x : i32 ) -> i32 {
43
+ if x == std:: i32:: MIN {
44
+ return 0 ;
45
+ }
46
+ let mut y = x. abs ( ) ;
47
+ let mut res: i32 = 0 ;
48
+ while y > 0 {
49
+ if res. checked_mul ( 10 ) . is_none ( ) {
50
+ return 0 ;
51
+ }
52
+ res = res * 10 ;
53
+ if res. checked_add ( y % 10 ) . is_none ( ) {
54
+ return 0 ;
55
+ }
56
+ res = res + y % 10 ;
57
+ y = y / 10 ;
58
+ }
59
+ if x < 0 {
60
+ -res
61
+ } else {
62
+ res
63
+ }
64
+ }
65
+ }
66
+
67
+ // submission codes end
68
+
69
+ #[ cfg( test) ]
70
+ mod tests {
71
+ use super :: * ;
72
+
73
+ #[ test]
74
+ fn test_7 ( ) {
75
+ assert_eq ! ( Solution :: reverse( 0 ) , 0 ) ;
76
+ assert_eq ! ( Solution :: reverse( std:: i32 :: MAX ) , 0 ) ;
77
+ assert_eq ! ( Solution :: reverse( 123 ) , 321 ) ;
78
+ assert_eq ! ( Solution :: reverse( -123 ) , -321 ) ;
79
+ }
80
+ }
You can’t perform that action at this time.
0 commit comments