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;
}
相关推荐
代码游侠10 小时前
学习笔记——GPIO按键与中断系统
c语言·开发语言·arm开发·笔记·嵌入式硬件·学习·重构
l1t10 小时前
对clickhouse给出的二分法求解Advent of Code 2025第10题 电子工厂 第二部分的算法理解
数据库·算法·clickhouse
Tisfy10 小时前
LeetCode 3315.构造最小位运算数组 II:位运算
算法·leetcode·题解·位运算
YuTaoShao10 小时前
【LeetCode 每日一题】1292. 元素和小于等于阈值的正方形的最大边长
算法·leetcode·职场和发展
保护我方头发丶10 小时前
hard_link.bat(个人用)
c语言
Remember_99310 小时前
【数据结构】深入理解Map和Set:从搜索树到哈希表的完整解析
java·开发语言·数据结构·算法·leetcode·哈希算法·散列表
浅念-10 小时前
C++第一课
开发语言·c++·经验分享·笔记·学习·算法
你爱写程序吗(新H)10 小时前
基于单片机的洗衣机控制系统设计 单片机洗衣机控制(设计+文档)
c语言·汇编·单片机·嵌入式硬件·matlab
charlie11451419110 小时前
现代嵌入式C++教程:对象池(Object Pool)模式
开发语言·c++·学习·算法·嵌入式·现代c++·工程实践
HABuo10 小时前
【linux进程控制(三)】进程程序替换&自己实现一个bash解释器
linux·服务器·c语言·c++·ubuntu·centos·bash