From a1f4780dc28eb97db06997cfa2cfaa0b6e682dc1 Mon Sep 17 00:00:00 2001 From: openset Date: Tue, 12 Nov 2019 14:05:26 +0800 Subject: [PATCH] Add: Excel Sheet Column Title --- .../excel_sheet_column_title.go | 13 ++++++++++++- .../excel_sheet_column_title_test.go | 10 +++++++++- 2 files changed, 21 insertions(+), 2 deletions(-) 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 82cbd34ac..132103290 100644 --- a/problems/excel-sheet-column-title/excel_sheet_column_title.go +++ b/problems/excel-sheet-column-title/excel_sheet_column_title.go @@ -1,8 +1,19 @@ -package excel_sheet_column_title +package problem_168 +// Solution 1: recursive func convertToTitle(n int) string { if n--; n < 26 { return string(n + 'A') } return convertToTitle(n/26) + string(n%26+'A') } + +// Solution 2: iteration +func convertToTitle2(n int) string { + ans := "" + for ; n > 0; n /= 26 { + n-- + ans = string(n%26+'A') + ans + } + return ans +} 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 9ce8afc35..94996f96c 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,4 +1,4 @@ -package excel_sheet_column_title +package problem_168 import "testing" @@ -46,10 +46,18 @@ func TestConvertToTitle(t *testing.T) { expected: "XYZ", }, } + // Solution 1 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) } } + // Solution 2 + for _, tc := range tests { + output := convertToTitle2(tc.input) + if output != tc.expected { + t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected) + } + } }