LeetCode //C - 168. Excel Sheet Column Title

168. Excel Sheet Column Title

Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet.

For example:

A -> 1

B -> 2

C -> 3

...

Z -> 26

AA -> 27

AB -> 28

...

Example 1:

Input: columnNumber = 1
Output: "A"

Example 2:

Input: columnNumber = 28
Output: "AB"

Example 3:

Input: columnNumber = 701
Output: "ZY"

Constraints:
  • 1 < = c o l u m n N u m b e r < = 2 31 − 1 1 <= columnNumber <= 2^{31} - 1 1<=columnNumber<=231−1

From: LeetCode

Link: 168. Excel Sheet Column Title


Solution:

Ideas:

1. Memory Allocation: We allocate memory for the result string. Since column numbers are large, we assume a reasonable size (8 characters) to cover most cases.

2. Loop through the column number: While columnNumber is greater than 0:

  • Decrement columnNumber by 1 to shift it to a 0-based index.
  • Compute the remainder when columnNumber is divided by 26. This gives us the position in the alphabet.
  • Convert this remainder to the corresponding character by adding it to the ASCII value of 'A'.
  • Store the character in the result array and increment the index.
  • Update columnNumber by integer division by 26.

3. String Reversal: After forming the result, the string is reversed because characters are added from the least significant digit to the most significant digit.

4. Return the Result: The result is returned after null-terminating it.

Code:
c 复制代码
char* convertToTitle(int columnNumber) {
    char* result = (char*)malloc(8 * sizeof(char));  // Allocate memory for the result
    int index = 0;
    
    while (columnNumber > 0) {
        columnNumber--;  // Adjust to 0-indexed
        int remainder = columnNumber % 26;
        result[index++] = 'A' + remainder;
        columnNumber /= 26;
    }
    
    result[index] = '\0';  // Null-terminate the string
    
    // Reverse the string
    int len = strlen(result);
    for (int i = 0; i < len / 2; i++) {
        char temp = result[i];
        result[i] = result[len - 1 - i];
        result[len - 1 - i] = temp;
    }
    
    return result;
}
相关推荐
水蓝烟雨16 分钟前
[HOT 100] 2187. 完成旅途的最少时间
算法·hot 100
01_1 小时前
力扣hot100——LRU缓存(面试高频考题)
leetcode·缓存·面试·lru
菜鸟一枚在这1 小时前
深度解析建造者模式:复杂对象构建的优雅之道
java·开发语言·算法
gyeolhada2 小时前
2025蓝桥杯JAVA编程题练习Day5
java·数据结构·算法·蓝桥杯
阿巴~阿巴~2 小时前
多源 BFS 算法详解:从原理到实现,高效解决多源最短路问题
开发语言·数据结构·c++·算法·宽度优先
给bug两拳2 小时前
Day9 25/2/22 SAT
算法
_Itachi__3 小时前
LeetCode 热题 100 73. 矩阵置零
算法·leetcode·矩阵
waicsdn_haha3 小时前
Visual Studio Code 2025 安装与高效配置教程
c语言·ide·windows·vscode·微软·编辑器·win7
夏末秋也凉3 小时前
力扣-贪心-376 摆动序列
算法·leetcode