问题来源:https://leetcode.com/problems/excel-sheet-column-number/
/**
*
* <p>
* ClassName ExcelSheetColumnNumber
* </p>
* <p>
* Description Related to question Excel Sheet Column Title
*
* Given a column title as appear in an Excel sheet, return its corresponding column number.
*
* For example:
*
* A -> 1<br/>
* B -> 2<br/>
* C -> 3<br/>
* ... <br/>
* Z -> 26<br/>
* AA -> 27<br/>
* AB -> 28<br/>
* </p>
*
* @author TKPad wangx89@126.com
* <p>
* Date 2015年3月25日 下午8:57:41
* </p>
* @version V1.0.0
*
*/
public class ExcelSheetColumnNumber {
// 我的解题思路是将字符串转成字符数组,然后将其看成是逢26进一,与我们正常使用的逢10进一是一样的,只不过进制不同而已
// 比如,AB->28,对每一位单独操作AB-AA=01->每位加1->12->1*26^1+2*26^0
// 比如,BB->54,对每一位单独操作BB-AA=11->每位加1->22->2*26^1+2*26^0
public int titleToNumber(String s) {
if (null == s || 0 == s.length()) {
return 0;
}
char[] charArray = s.toCharArray();
int pow = 0;
int sum = 0;
for (int i = charArray.length - 1; i >= 0; i--) {
int temp = charArray[i] - ‘A‘ + 1;
int temp2 = (int) Math.pow(26, pow);
pow++;
sum += temp * temp2;
}
return sum;
}
public static void main(String[] args) {
int titleToNumber = new ExcelSheetColumnNumber().titleToNumber("BBB");
System.out.println(titleToNumber);
}
}
原文:http://blog.csdn.net/shijiebei2009/article/details/44628805