【EASY】Excel Sheet Column Number

发布于: 2018-12-11 13:52
阅读: 44
评论: 0
喜欢: 0

问题

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 

分析过程

  • 输入:Excel 的行号
  • 输出:十进制数
  • 思路:本质为进制转换,26 进制转 10 进制

解决方法

static bool err = false;
int excel2Int(char *str) {
    size_t len = strlen(str);
    int result = 0;
    for (int i = 0; i < len; i++) {
        char c = str[i];
        if (c >= 'A' && c <= 'Z') {
            result = result * 26 + (c - 'A' + 1);
        } else {
            err = true;
            return 0;
        }
    }
    
    return result;
}

int main() {
    char input[] = "AB";
    int result = excel2Int(input);
    if (err) {
        printf("err\n");
    } else {
        printf("%d\n", result);
    }
}

Thanks for reading.

All the best wishes for you! 💕