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;
}
相关推荐
麻瓜code24 分钟前
【LeetCode】相交链表:双指针法,一次遍历找到交点
算法·leetcode·链表
zander2581 小时前
LeetCode 5. 最长回文子串
算法
hanlin032 小时前
刷题笔记:力扣第84题-柱状图中最大的矩形
笔记·算法·leetcode
青少儿编程课堂3 小时前
威佐夫博弈(双堆取子游戏)解析
c++·python·算法·bfs·信息学竞赛
辰烨chenye7 小时前
LeetCode Hot 100 题解 · 普通数组篇
算法·leetcode·职场和发展
hqyjzsb10 小时前
零 AI 项目经验,学 Python 转型 AI 的正确顺序是什么?
开发语言·人工智能·python·算法·职场和发展·数据挖掘·数据分析
辰烨chenye10 小时前
LeetCode Hot 100 题解 · 二分篇
java·算法·leetcode
微功夫信息技术10 小时前
分层多智能体强化学习驱动的非急救转运公平 - 效率统一调度系统研究与实践
人工智能·学习·算法·动态规划
T1mzhou10 小时前
ARM64 Linux 6.10内核启动流程7-ioremap和readl writel
linux·服务器·c语言
sanjiaomao33311 小时前
从论文公式到Python实现:用单元测试校验滑动平均算法
python·算法·单元测试