
问题
给定一个Excel表格中的列名称,返回其相应的列序号。
例如,
A -> 1
B -> 2
C -> 3
…
Z -> 26
AA -> 27
AB -> 28
…
输入: “A”
输出: 1
输入: “AB”
输出: 28
输入: “ZY”
输出: 701
致谢:特别感谢 @ts 添加此问题并创建所有测试用例。
Given a column title as appear in an Excel sheet, return its corresponding column number.
For example:
A -> 1
B -> 2
C -> 3
…
Z -> 26
AA -> 27
AB -> 28
…
Input: “A”
Output: 1
Input: “AB”
Output: 28
Input: “ZY”
Output: 701
示例
public class Program { public static void Main(string[] args) { var s = "ZY"; var res = TitleToNumber(s); Console.WriteLine(res); Console.ReadKey(); } private static int TitleToNumber(string s) { var res = 0; for(int i = s.Length - 1; i >= 0; i--) { res += (s[i] - 64) * (int)Math.Pow(26, s.Length - i - 1); } return res; } }
以上给出1种算法实现,以下是这个案例的输出结果:
701
分析:
显而易见,以上算法的时间复杂度为: 。
本文由 .Net中文网 原创发布,欢迎大家踊跃转载。
转载请注明本文地址:https://www.byteflying.com/archives/3852。