问题
该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3850 访问。
给定一个正整数,返回它在 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"
示例
该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3850 访问。
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种算法实现,以下是这个案例的输出结果:
该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3850 访问。
ZY
ZB
RFU
分析:
显而易见,以上3种算法的时间复杂度均为: 。