百度面试题-类似Excel列名的位置查找问题

4 views
Skip to first unread message

stone54321277

unread,
Jan 13, 2010, 8:18:24 AM1/13/10
to Wind Stone
序列Seq=[a,b,…z,aa,ab…az,ba,bb,…bz,…,za,zb,…zz,aaa,…] 类似与excel的排列,任意给出一个字
符串s=[a-z]+(由a-z字符组成的任意长度字符串),请问s是序列Seq的第几个
火龙果:
A: 1
B: 2
...
Z: 26
AA = 1 * 26^1 + 1 = 27
AAA = 1 * 26^2 + 1 * 26^1 + 1 = 703
将字母序列从右往左依次编号为 i,最右边一位为 0,最左边一位为 n,
在 i 位上字母的值为 K[i],则序列为:

相当于26进制。
查看复制到剪切板打印
public class T {
public static void main(String[] args) {
int n = letter2Number("ab");
System.out.println(n);
}

public static int letter2Number(String letters) {
if (!letters.matches("[a-zA-Z]+")) {
throw new IllegalArgumentException("Format ERROR!");
}
char[] chs = letters.toLowerCase().toCharArray();
int result = 0;
for (int i = chs.length - 1, p = 1; i >= 0; i--) {
result += getNum(chs[i]) * p;
p *= 26;
}
return result;
}

private static int getNum(char c) {
return c - 'a' + 1;
}

}
public class T {
public static void main(String[] args) {
int n = letter2Number("ab");
System.out.println(n);
}
public static int letter2Number(String letters) {
if (!letters.matches("[a-zA-Z]+")) {
throw new IllegalArgumentException("Format ERROR!");
}
char[] chs = letters.toLowerCase().toCharArray();
int result = 0;
for (int i = chs.length - 1, p = 1; i >= 0; i--) {
result += getNum(chs[i]) * p;
p *= 26;
}
return result;
}
private static int getNum(char c) {
return c - 'a' + 1;
}
}

Reply all
Reply to author
Forward
0 new messages