File tree Expand file tree Collapse file tree 4 files changed +14
-6
lines changed
exercises/02_basic_calculator Expand file tree Collapse file tree 4 files changed +14
-6
lines changed Original file line number Diff line number Diff line change @@ -12,3 +12,6 @@ resolver = "2"
12
12
# regardless of the "global" setting for `overflow-checks` on the `dev` profile.
13
13
[profile .dev .package .copy ]
14
14
overflow-checks = true
15
+
16
+ [profile .dev ]
17
+ overflow-checks = false
Original file line number Diff line number Diff line change 1
1
// Rewrite the factorial function using a `for` loop.
2
2
pub fn factorial ( n : u32 ) -> u32 {
3
- todo ! ( )
3
+ let mut result = 1 ;
4
+
5
+ for i in 1 ..=n {
6
+ result *= i;
7
+ }
8
+ result
4
9
}
5
10
6
11
#[ cfg( test) ]
Original file line number Diff line number Diff line change 1
1
pub fn factorial ( n : u32 ) -> u32 {
2
- let mut result = 1 ;
2
+ let mut result: u32 = 1 ;
3
3
for i in 1 ..=n {
4
4
// Use saturating multiplication to stop at the maximum value of u32
5
5
// rather than overflowing and wrapping around
6
- result *= i ;
6
+ result = result . saturating_mul ( i ) ;
7
7
}
8
8
result
9
9
}
Original file line number Diff line number Diff line change @@ -6,7 +6,7 @@ mod tests {
6
6
7
7
#[ test]
8
8
fn u16_to_u32 ( ) {
9
- let v: u32 = todo ! ( ) ;
9
+ let v: u32 = 47u16 as u32 ;
10
10
assert_eq ! ( 47u16 as u32 , v) ;
11
11
}
12
12
@@ -24,14 +24,14 @@ mod tests {
24
24
// You could solve this by using exactly the same expression as above,
25
25
// but that would defeat the purpose of the exercise. Instead, use a genuine
26
26
// `i8` value that is equivalent to `255` when converted from `u8`.
27
- let y: i8 = todo ! ( ) ;
27
+ let y: i8 = - 1 ;
28
28
29
29
assert_eq ! ( x, y) ;
30
30
}
31
31
32
32
#[ test]
33
33
fn bool_to_u8 ( ) {
34
- let v: u8 = todo ! ( ) ;
34
+ let v: u8 = 1 ;
35
35
assert_eq ! ( true as u8 , v) ;
36
36
}
37
37
}
You can’t perform that action at this time.
0 commit comments