File tree 2 files changed +61
-0
lines changed
2 files changed +61
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ * [0405] convert-a-number-to-hexadecimal
3
+ */
4
+
5
+ pub struct Solution { }
6
+
7
+ // solution impl starts here
8
+
9
+ impl Solution {
10
+ pub fn to_hex ( num : i32 ) -> String {
11
+ if num == 0 {
12
+ return "0" . to_string ( ) ;
13
+ }
14
+ let s = "0123456789abcdef" ;
15
+ let m = 0x0000000f ;
16
+ let mut n: i64 = num as i64 & 0xffffffff ;
17
+ let mut r = String :: new ( ) ;
18
+ while n > 0 {
19
+ r. push ( s. chars ( ) . nth ( ( n & m) as usize ) . unwrap ( ) ) ;
20
+ n >>= 4 ;
21
+ }
22
+ r. chars ( ) . rev ( ) . collect :: < String > ( )
23
+ }
24
+ }
25
+
26
+ // solution impl ends here
27
+
28
+ // solution tests starts here
29
+
30
+ #[ cfg( test) ]
31
+ mod tests {
32
+ use super :: * ;
33
+
34
+ #[ test]
35
+ fn test_case0 ( ) {
36
+ assert_eq ! ( Solution :: to_hex( 26 ) , "1a" ) ;
37
+ }
38
+
39
+ #[ test]
40
+ fn test_case1 ( ) {
41
+ assert_eq ! ( Solution :: to_hex( -1 ) , "ffffffff" ) ;
42
+ }
43
+
44
+ #[ test]
45
+ fn test_case2 ( ) {
46
+ assert_eq ! ( Solution :: to_hex( -2 ) , "fffffffe" ) ;
47
+ }
48
+
49
+ #[ test]
50
+ fn test_case3 ( ) {
51
+ assert_eq ! ( Solution :: to_hex( 0 ) , "0" ) ;
52
+ }
53
+
54
+ #[ test]
55
+ fn test_case4 ( ) {
56
+ assert_eq ! ( Solution :: to_hex( 111111 ) , "1b207" ) ;
57
+ }
58
+ }
59
+
60
+ // solution tests ends here
Original file line number Diff line number Diff line change @@ -11,6 +11,7 @@ mod a0145_binary_tree_postorder_traversal;
11
11
mod a0172_factorial_trailing_zeroes;
12
12
mod a0400_nth_digit;
13
13
mod a0404_sum_of_left_leaves;
14
+ mod a0405_convert_a_number_to_hexadecimal;
14
15
mod a0617_merge_two_binary_trees;
15
16
mod a0643_maximum_average_subarray_i;
16
17
mod a0929_unique_email_addresses;
You can’t perform that action at this time.
0 commit comments