分析
难度 易
来源
https://leetcode.com/problems/excel-sheet-column-number
题目
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
…
Example 1:
Input: “A”
Output: 1
Example 2:
Input: “AB”
Output: 28
Example 3:
Input: “ZY”
Output: 701
解答
Runtime: 1 ms, faster than 100.00% of Java online submissions for Excel Sheet Column Number.
package LeetCode;
public class L171_ExcelSheetColumnNumber {
public int titleToNumber(String s) {
int len=s.length();
int colNum=0;
int base=1;//当前位的1表示的大小
for(int i=len-1;i>=0;i--){
colNum+=(int)(s.charAt(i)-64)*base;
base*=26;
}
return colNum;
}
public static void main(String[] args){
L171_ExcelSheetColumnNumber l171=new L171_ExcelSheetColumnNumber();
String s="AB";
System.out.println(l171.titleToNumber(s));
}
}