From 2c193f140d939b6c3dd7fb058d6cd130f3728dd4 Mon Sep 17 00:00:00 2001 From: Bauke Date: Sat, 9 Apr 2022 13:04:21 +0200 Subject: [PATCH] Solve excel-sheet-column-title. --- source/excel_sheet_column_title/mod.rs | 18 ++++++++++++++++++ source/lib.rs | 1 + tests/excel_sheet_column_title.rs | 11 +++++++++++ 3 files changed, 30 insertions(+) create mode 100644 source/excel_sheet_column_title/mod.rs create mode 100644 tests/excel_sheet_column_title.rs diff --git a/source/excel_sheet_column_title/mod.rs b/source/excel_sheet_column_title/mod.rs new file mode 100644 index 0000000..8de1795 --- /dev/null +++ b/source/excel_sheet_column_title/mod.rs @@ -0,0 +1,18 @@ +pub fn convert_to_title(column: i32) -> String { + let radix = 26; + + let mut column = column as u32; + let mut result = vec![]; + + while column != 0 { + // Subtract 1 so the number 0 would equal the value 1. + let value = (column - 1) % radix; + column = (column - 1) / radix; + + // Add 65 so the modulo'd value will be in the 65 through 90 character range + // (upppercase letters). + result.push(char::from_u32(value + 65).unwrap()); + } + + result.into_iter().rev().collect::() +} diff --git a/source/lib.rs b/source/lib.rs index a3d547a..1814c68 100644 --- a/source/lib.rs +++ b/source/lib.rs @@ -1,5 +1,6 @@ pub mod add_binary; pub mod excel_sheet_column_number; +pub mod excel_sheet_column_title; pub mod implement_strstr; pub mod length_of_last_word; pub mod longest_common_prefix; diff --git a/tests/excel_sheet_column_title.rs b/tests/excel_sheet_column_title.rs new file mode 100644 index 0000000..1b9d734 --- /dev/null +++ b/tests/excel_sheet_column_title.rs @@ -0,0 +1,11 @@ +use leetcode::excel_sheet_column_title::convert_to_title; + +use test_case::test_case; + +#[test_case(1, "A"; "minimum")] +#[test_case(i32::MAX, "FXSHRXW"; "maximum")] +#[test_case(28, "AB"; "double")] +#[test_case(1377, "AZY"; "triple")] +fn test_excel_sheet_column_title(input: i32, expected: &str) { + assert_eq!(convert_to_title(input), expected); +}