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) + } + } +}