171. Excel Sheet Column Number
Related to question
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
如题,题目可理解为二十六进制的转化。
代码如下:
public class Solution { public int titleToNumber(String s) { int num=0; int[] a =new int[s.length()]; for(int j = 0; j < s.length(); j++){ a[j]=s.charAt(j)-'A'+1; num=num+Pow(26,s.length()-j-1)*a[j]; } return num; } private static int Pow(int i, int j){ if(j==0) return 1; return i*Pow(i,j-1); }}或是比较灵巧的方法:如下:
public class Solution { public int titleToNumber(String s) { int num=0; for(int j = 0; j < s.length(); j++){ num=num*26+s.charAt(j)-"A"+1; } return num; } }