From a581d27d24581394300e316f636d9ff5e5c480a4 Mon Sep 17 00:00:00 2001 From: openset Date: Tue, 26 Feb 2019 11:06:36 +0800 Subject: [PATCH] Add: Excel Sheet Column Number --- .../excel_sheet_column_number.go | 9 ++++ .../excel_sheet_column_number_test.go | 49 +++++++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/problems/excel-sheet-column-number/excel_sheet_column_number.go b/problems/excel-sheet-column-number/excel_sheet_column_number.go index 98817f5c9..6061154dc 100644 --- a/problems/excel-sheet-column-number/excel_sheet_column_number.go +++ b/problems/excel-sheet-column-number/excel_sheet_column_number.go @@ -1 +1,10 @@ package excel_sheet_column_number + +func titleToNumber(s string) int { + ans := 0 + for _, c := range s { + ans *= 26 + ans += int(c) - 'A' + 1 + } + return ans +} diff --git a/problems/excel-sheet-column-number/excel_sheet_column_number_test.go b/problems/excel-sheet-column-number/excel_sheet_column_number_test.go index 98817f5c9..476dd0228 100644 --- a/problems/excel-sheet-column-number/excel_sheet_column_number_test.go +++ b/problems/excel-sheet-column-number/excel_sheet_column_number_test.go @@ -1 +1,50 @@ package excel_sheet_column_number + +import "testing" + +type caseType struct { + input string + expected int +} + +func TestTitleToNumber(t *testing.T) { + tests := [...]caseType{ + { + input: "A", + expected: 1, + }, + { + input: "C", + expected: 3, + }, + { + input: "Z", + expected: 26, + }, + { + input: "AA", + expected: 27, + }, + { + input: "AB", + expected: 28, + }, + { + input: "ZY", + expected: 701, + }, { + input: "AAA", + expected: 703, + }, + { + input: "XYZ", + expected: 16900, + }, + } + for _, tc := range tests { + output := titleToNumber(tc.input) + if output != tc.expected { + t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected) + } + } +}