From d35c46bacf9b8ad80b4eddda466e772f1b8527bf Mon Sep 17 00:00:00 2001 From: openset Date: Tue, 26 Feb 2019 12:01:51 +0800 Subject: [PATCH] Add: Excel Sheet Column Title --- .../excel_sheet_column_title.go | 7 +++ .../excel_sheet_column_title_test.go | 54 +++++++++++++++++++ 2 files changed, 61 insertions(+) diff --git a/problems/excel-sheet-column-title/excel_sheet_column_title.go b/problems/excel-sheet-column-title/excel_sheet_column_title.go index 05ad7ad45..954d1d263 100644 --- a/problems/excel-sheet-column-title/excel_sheet_column_title.go +++ b/problems/excel-sheet-column-title/excel_sheet_column_title.go @@ -1 +1,8 @@ package excel_sheet_column_title + +func convertToTitle(n int) string { + if n < 27 { + return string(n - 1 + 'A') + } + return convertToTitle((n-1)/26) + string((n-1)%26+'A') +} diff --git a/problems/excel-sheet-column-title/excel_sheet_column_title_test.go b/problems/excel-sheet-column-title/excel_sheet_column_title_test.go index 05ad7ad45..9ce8afc35 100644 --- a/problems/excel-sheet-column-title/excel_sheet_column_title_test.go +++ b/problems/excel-sheet-column-title/excel_sheet_column_title_test.go @@ -1 +1,55 @@ package excel_sheet_column_title + +import "testing" + +type caseType struct { + input int + expected string +} + +func TestConvertToTitle(t *testing.T) { + tests := [...]caseType{ + { + input: 1, + expected: "A", + }, + { + input: 3, + expected: "C", + }, + { + input: 26, + expected: "Z", + }, + { + input: 52, + expected: "AZ", + }, + { + input: 27, + expected: "AA", + }, + { + input: 28, + expected: "AB", + }, + { + input: 701, + expected: "ZY", + }, + { + input: 703, + expected: "AAA", + }, + { + input: 16900, + expected: "XYZ", + }, + } + for _, tc := range tests { + output := convertToTitle(tc.input) + if output != tc.expected { + t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected) + } + } +}