码迷,mamicode.com
首页 > 其他好文 > 详细

Excel Sheet Column Number

时间:2014-12-31 10:09:13      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:leetcode   算法   math   

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/42290079

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 


思路:

(1)题意为给出Excel中对应列的字符求出该字符对应的整数。

(2)这道简单题考查的是“二十六进制”的问题(非真正二十六进制)。不难发现,每当超过26时,和十进制类似会发生变化,这里不对其解释。

(3)考虑到简单快捷,直接将26个字符对应的整数值存入一个Map中。需要说明的是算法中用到了Math类的power()方法,该方法是幂次方函数。

         例如对于字符“ABC”来说,求解过程为:

         count = 0 + 1 * Math.power(26, 2) = 676;

         count = 676 + 2 * Math.power(26, 1) = 728;

         count = 728 + 3 * Math.power(26, 0) = 731;

(4)希望本文对你有所帮助。


算法代码实现如下:

public static int titleToNumber(String s) {
	Map<String, Integer> all = new HashMap<String, Integer>();
	all.put("A", 1);
	all.put("B", 2);
	all.put("C", 3);
	all.put("D", 4);
	all.put("E", 5);
	all.put("F", 6);
	all.put("G", 7);
	all.put("H", 8);
	all.put("I", 9);
	all.put("J", 10);
	all.put("K", 11);
	all.put("L", 12);
	all.put("M", 13);
	all.put("N", 14);
	all.put("O", 15);
	all.put("P", 16);
	all.put("Q", 17);
	all.put("R", 18);
	all.put("S", 19);
	all.put("T", 20);
	all.put("U", 21);
	all.put("V", 22);
	all.put("W", 23);
	all.put("X", 24);
	all.put("Y", 25);
	all.put("Z", 26);

	if (s == null)
		return -1;
	int len = s.length();
	int sum = 0;
	int power = len - 1;
	for (int i = 0; i < len; i++) {
		int curr = all.get(String.valueOf(s.charAt(i)));
		sum += curr * Math.pow(all.size(), power);
		power--;
	}
	return sum;
}


Excel Sheet Column Number

标签:leetcode   算法   math   

原文地址:http://blog.csdn.net/pistolove/article/details/42290079

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!