File tree 2 files changed +73
-0
lines changed
2 files changed +73
-0
lines changed Original file line number Diff line number Diff line change @@ -155,3 +155,4 @@ mod n0164_maximum_gap;
155
155
mod n0165_compare_version_numbers;
156
156
mod n0166_fraction_to_recurring_decimal;
157
157
mod n0167_two_sum_ii_input_array_is_sorted;
158
+ mod n0168_excel_sheet_column_title;
Original file line number Diff line number Diff line change
1
+ /**
2
+ * [168] Excel Sheet Column Title
3
+ *
4
+ * Given a positive integer, return its corresponding column title as appear in an Excel sheet.
5
+ *
6
+ * For example:
7
+ *
8
+ *
9
+ * 1 -> A
10
+ * 2 -> B
11
+ * 3 -> C
12
+ * ...
13
+ * 26 -> Z
14
+ * 27 -> AA
15
+ * 28 -> AB
16
+ * ...
17
+ *
18
+ *
19
+ * Example 1:
20
+ *
21
+ *
22
+ * Input: 1
23
+ * Output: "A"
24
+ *
25
+ *
26
+ * Example 2:
27
+ *
28
+ *
29
+ * Input: 28
30
+ * Output: "AB"
31
+ *
32
+ *
33
+ * Example 3:
34
+ *
35
+ *
36
+ * Input: 701
37
+ * Output: "ZY"
38
+ *
39
+ */
40
+ pub struct Solution { }
41
+
42
+ // submission codes start here
43
+
44
+ impl Solution {
45
+ pub fn convert_to_title ( n : i32 ) -> String {
46
+ let base = 26 ;
47
+ let mut n = n;
48
+ let mut res = Vec :: new ( ) ;
49
+ while n > 0 {
50
+ let mut code = ( n % base) as u8 ;
51
+ n = n / base;
52
+ if code == 0 { n -= 1 ; code = base as u8 ; } ;
53
+ let alphabetic = ( ( 'A' as u8 ) + ( code - 1_u8 ) ) as char ;
54
+ res. push ( alphabetic) ;
55
+ }
56
+ res. reverse ( ) ;
57
+ res. into_iter ( ) . collect ( )
58
+ }
59
+ }
60
+
61
+ // submission codes end
62
+
63
+ #[ cfg( test) ]
64
+ mod tests {
65
+ use super :: * ;
66
+
67
+ #[ test]
68
+ fn test_168 ( ) {
69
+ assert_eq ! ( Solution :: convert_to_title( 28 ) , "AB" . to_owned( ) ) ;
70
+ assert_eq ! ( Solution :: convert_to_title( 1 ) , "A" . to_owned( ) ) ;
71
+ }
72
+ }
You can’t perform that action at this time.
0 commit comments