eimhee 发表于 2013-1-27 04:45:52

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

原文:http://topic.csdn.net/u/20080923/11/ee117de0-38ec-4d34-802d-64c7a0f34b7f.html

序列Seq= 类似与excel的排列,任意给出一个字符串s=+(由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,则序列为:
http://p.blog.csdn.net/images/p_blog_csdn_net/java2000_net/EntryImages/20080924/2008-09-24_055358.gif

相当于26进制。

<div class="highlighter">
[*]public class T {
[*]  public static void main(String[] args) {
[*]    int n = letter2Number("ab");
[*]    System.out.println(n);
[*]  }
[*]<span />
[*]  public static int letter2Number(String letters) {
[*]    if (!letters.matches("+")) {
[*]      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) * p;
[*]      p *= 26;
[*]    }
[*]    return result;
[*]  }
[*]<span />
[*]  private static int getNum(char c) {
[*]    return c - 'a' + 1;
[*]  }
[*]<span />
[*]}
页: [1]
查看完整版本: 百度面试题-类似Excel列名的位置查找问题