题目:
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 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28
题意:就是给定一个字母组合,然后输出它对应的值。这道题不太难,可以寻找数学规律。最后它的数学规律是num = 26^n1 + n2,就是n1表示次方,而后面的n2表示就是在那一位上的值与'A'的差距,也就是值。具体的代码如下:
public class Ugly
{
public static int titleToNumber(String s)
{
int length = s.length();
int sum = 0;
for(int i = length - 1; i >= 0; i--)
{
sum = (int) (sum + (s.charAt(i) - 'A' + 1) * Math.pow(26, Math.abs(i + 1 - length)));
}
return sum;
}
public static void main(String args[])
{
String str = new String("A");
System.out.println(titleToNumber(str));
}
}