C#LeetCode刷題之#168-Excel表列名稱(Excel Sheet Column Title)
阿新 • • 發佈:2018-12-12
問題
給定一個正整數,返回它在 Excel 表中相對應的列名稱。
例如,
1 -> A 2 -> B 3 -> C ... 26 -> Z 27 -> AA 28 -> AB ...
輸入: 1
輸出: "A"
輸入: 28
輸出: "AB"
輸入: 701
輸出: "ZY"
Given a positive integer, return its corresponding column title as appear in an Excel sheet.
For example:
1 -> A 2 -> B 3 -> C ... 26 -> Z 27 -> AA 28 -> AB ...
Input: 1
Output: "A"
Input: 28
Output: "AB"
Input: 701
Output: "ZY"
示例
public class Program { public static void Main(string[] args) { var n = 701; var res = ConvertToTitle(n); Console.WriteLine(res); n = 678; res = ConvertToTitle2(n); Console.WriteLine(res); n = 12345; res = ConvertToTitle3(n); Console.WriteLine(res); Console.ReadKey(); } private static string ConvertToTitle(int n) { if(n <= 26) return ((char)(n + 'A' - 1)).ToString(); if(n % 26 == 0) { return ConvertToTitle(n / 26 - 1) + 'Z'; } else { return ConvertToTitle(n / 26) + ConvertToTitle(n % 26); } } private static string ConvertToTitle2(int n) { if(n <= 0) return ""; return ConvertToTitle((n - 1) / 26) + (char)((n - 1) % 26 + 'A'); } private static string ConvertToTitle3(int n) { var res = string.Empty; while(n > 0) { var s = (char)((n - 1) % 26 + 'A'); res = s + res; n = (n - 1) / 26; } return res; } }
以上給出3種演算法實現,以下是這個案例的輸出結果:
ZY
ZB
RFU
分析:
顯而易見,以上3種演算法的時間複雜度均為: 。