算法-转化Excel列名为下标

2024-5-31 diaba 算法

package jiucaiyuan.net;

/**
 * 题目:
 *  Excel表头列名:A、B、C、。。。、Z、AA、AB、。。。、AZ、BA、BB、。。。、BZ、CA、CB、。。。
 *  如果A对应的下标是0,B对应的是1,。。。、Z对应的是25、AA对应的是26、。。。
 *  实现一个方法,输入列名,输出下标
 */
public class LetterToNumberConverter {

    public static int convertToNumber(String letters) {
        int result = 0;
        int base = 1; // 初始基数为1,即26的0次幂

        for (int i = letters.length() - 1; i >= 0; i--) {
            char c = letters.charAt(i);
            int value = c - 'A'; // 计算当前字母对应的数字(0-25)
            if (i != letters.length() -1) {
                value += 1;
            }
            result += value * base; // 累加当前字母的值到结果中
            base *= 26; // 更新基数为下一个字母的幂次
        }

        return result;
    }

    public static void main(String[] args) {
        String test = "AB";
        int number = convertToNumber(test);
        System.out.println("The number for \"" + test + "\" is: " + number); // 应该输出 52

        test = "A";
        number = convertToNumber(test);
        System.out.println("The number for \"" + test + "\" is: " + number); // 应该输出 52

        test = "B";
        number = convertToNumber(test);
        System.out.println("The number for \"" + test + "\" is: " + number); // 应该输出 52


        test = "Z";
        number = convertToNumber(test);
        System.out.println("The number for \"" + test + "\" is: " + number); // 应该输出 52


        test = "BA";
        number = convertToNumber(test);
        System.out.println("The number for \"" + test + "\" is: " + number); // 应该输出 52

        test = "BB";
        number = convertToNumber(test);
        System.out.println("The number for \"" + test + "\" is: " + number); // 应该输出 52

        test = "AA";
        number = convertToNumber(test);
        System.out.println("The number for \"" + test + "\" is: " + number); // 应该输出 52

        test = "AAA";
        number = convertToNumber(test);
        System.out.println("The number for \"" + test + "\" is: " + number); // 应该输出 52
    }
}

发表评论:

Powered by emlog 京ICP备15045175号-1 Copyright © 2022