168. Excel Sheet Column Title

Posted 我的名字叫周周

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了168. Excel Sheet Column Title相关的知识,希望对你有一定的参考价值。

    /*
     * 168. Excel Sheet Column Title 
     * 12.12 by Mingyang
     *  一定要注意z为0的情况!!!
     */
    public static String convertToTitle(int n) {
        if (n <= 0)
            return " ";
        StringBuffer sb = new StringBuffer();
        while (n > 0) {
            int temp = n % 26;
            n = n / 26;
            if (temp == 0) {
                sb.insert(0, ‘Z‘);
                n--;
                continue;
            }
            sb.insert(0, Character.toChars(64 + temp));
        }
        return sb.toString();
    }
    // 网上简短写法,这里就避免了对26的讨论,因为把26-1=25以后,就可以直接加了
    public static String convertToTitle1(int n) {
        StringBuilder sb = new StringBuilder();
        while (n > 0) {
            n--;
            char ch = (char) (n % 26 + ‘A‘);
            n /= 26;
            sb.insert(0,ch);
        }
        return sb.toString();
    }
    /*
     * 那么关于进制问题,我们从26进制转换成10进制又如何解决呢?请看这道题目的想反问题
     */
    public int titleToNumber(String s) {
        int result = 0;
        for (int i = 0; i < s.length(); i++) {
            result = result * 26 + 1 + s.charAt(i) - ‘A‘;
        }
        return result;
    }

 

以上是关于168. Excel Sheet Column Title的主要内容,如果未能解决你的问题,请参考以下文章