From 50e994b2dc786628dd536ac14af101dc74614249 Mon Sep 17 00:00:00 2001 From: Bauke Date: Sat, 9 Apr 2022 10:47:39 +0200 Subject: [PATCH] Solve excel-sheet-column-number. --- source/excel_sheet_column_number/mod.rs | 18 ++++++++++++++++++ source/lib.rs | 1 + tests/excel_sheet_column_number.rs | 11 +++++++++++ 3 files changed, 30 insertions(+) create mode 100644 source/excel_sheet_column_number/mod.rs create mode 100644 tests/excel_sheet_column_number.rs diff --git a/source/excel_sheet_column_number/mod.rs b/source/excel_sheet_column_number/mod.rs new file mode 100644 index 0000000..01ae93f --- /dev/null +++ b/source/excel_sheet_column_number/mod.rs @@ -0,0 +1,18 @@ +pub fn title_to_number(title: String) -> i32 { + let mut result = 0; + + for (index, character) in title.chars().rev().enumerate() { + // Convert the character to a number and subtract 9 so A will equal 1. + let number = character.to_digit(36).unwrap() - 9; + + let n = if index == 0 { + number + } else { + 26_u32.pow(index as u32) * number + }; + + result += n; + } + + result as i32 +} diff --git a/source/lib.rs b/source/lib.rs index 3c40e85..a3d547a 100644 --- a/source/lib.rs +++ b/source/lib.rs @@ -1,4 +1,5 @@ pub mod add_binary; +pub mod excel_sheet_column_number; pub mod implement_strstr; pub mod length_of_last_word; pub mod longest_common_prefix; diff --git a/tests/excel_sheet_column_number.rs b/tests/excel_sheet_column_number.rs new file mode 100644 index 0000000..9c4969d --- /dev/null +++ b/tests/excel_sheet_column_number.rs @@ -0,0 +1,11 @@ +use leetcode::excel_sheet_column_number::title_to_number; + +use test_case::test_case; + +#[test_case("A", 1; "minimum")] +#[test_case("FXSHRXW", i32::MAX; "maximum")] +#[test_case("AB", 28; "double")] +#[test_case("AZY", 1377; "triple")] +fn test_excel_sheet_column_number(input: &str, expected: i32) { + assert_eq!(title_to_number(input.to_string()), expected); +}