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;
}
相关推荐
Lsk_Smion13 分钟前
Hot100(开刷) 之 长度最小的数组--删除倒数第N个链表--层序遍历
java·数据结构·算法·kotlin
luoganttcc15 分钟前
dim3 grid_size(2, 3, 4); dim3 block_size(4, 8, 4)算例
算法
WBluuue23 分钟前
Codeforces 1088 Div1+2(ABC1C2DEF)
c++·算法
蓝色的杯子31 分钟前
Python面试30分钟突击掌握-LeetCode3-Linked list
python·leetcode·面试
像素猎人32 分钟前
map<数据类型,数据类型> mp和unordered_map<数据类型,数据类型> ump的讲解,蓝桥杯OJ4567最大数目
c++·算法·蓝桥杯·stl·map
Narrastory33 分钟前
Note:强化学习(一)
人工智能·算法·强化学习
沐雪轻挽萤44 分钟前
1. C++17新特性-序章
java·c++·算法
郝学胜-神的一滴1 小时前
从链表到二叉树:树形结构的入门与核心性质解析
数据结构·c++·python·算法·链表
csdn_aspnet1 小时前
C语言 (QuickSort using Random Pivoting)使用随机枢轴的快速排序
c语言·算法·排序算法
玖釉-1 小时前
深入解析 meshoptimizer:基于 meshopt_computeSphereBounds 的层级包围球构建与 DAG 优化
c++·算法·图形渲染