Open carloscn opened 2 years ago
和leetcode168:Excel表列名称(excel-sheet-column-title) 是相反的,把ABCD转为数字。可以有两个思路,一个是从前往后加,一个是从后往前加。
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <math.h>
#include "buffer.h"
#include "utils.h"
#define METHOD_1 0 /* behind to front. */
#define METHOD_2 1 /* front to behind. */
#define C_OF(__c) ((int64_t)((__c) - 'A' + 1))
// Note, compiling the file, need to add `-lm' because of <math.h>.
// `gcc 09_excel-sheet-column-number_171.c utils.c -lm`
static int32_t excel_sheet_column_number(const char *str)
{
int32_t ret = 0;
int64_t out = 0;
size_t len = 0;
size_t pos = 0;
UTILS_CHECK_PTR(str);
len = strlen(str);
if (0 == len)
goto finish;
#if METHOD_1
do {
out += C_OF(str[--len]) * pow(26, pos++);
} while (len);
#elif METHOD_2
size_t i = 0;
for (i = 0; i < len; i ++) {
out = out * 26 + C_OF(str[i]);
}
#endif
LOG("the out put is %lld\n", out);
finish:
return ret;
}
int32_t main(void)
{
int32_t ret = 0;
int64_t val = 0;
ret = excel_sheet_column_number("A");
UTILS_CHECK_RET(ret);
ret = excel_sheet_column_number("AB");
UTILS_CHECK_RET(ret);
ret = excel_sheet_column_number("ZY");
UTILS_CHECK_RET(ret);
ret = excel_sheet_column_number("FXSHRXW");
UTILS_CHECK_RET(ret);
finish:
return ret;
}
问题描述:
给你一个字符串 columnTitle ,表示 Excel 表格中的列名称。返回 该列名称对应的列序号 。
例如:
A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ...
示例 1:
输入: columnTitle = "A" 输出: 1
示例 2: 输入: columnTitle = "AB" 输出: 28
示例 3: 输入: columnTitle = "ZY" 输出: 701 提示:
1 <= columnTitle.length <= 7 columnTitle 仅由大写英文组成 columnTitle 在范围 ["A", "FXSHRXW"] 内
来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/excel-sheet-column-number