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;
}
相关推荐
Tisfy1 分钟前
LeetCode 2536.子矩阵元素加 1:二维差分数组
算法·leetcode·矩阵
北邮刘老师30 分钟前
智能家居,需要的是“主控智能体”而不是“主控节点”
人工智能·算法·机器学习·智能体·智能体互联网
oioihoii32 分钟前
C++中有双向映射数据结构吗?Key和Value能否双向查找?
数据结构·c++·算法
nnn__nnn34 分钟前
图像分割技术全解析:从传统算法到深度学习的视觉分割革命
深度学习·算法·计算机视觉
_OP_CHEN1 小时前
算法基础篇:(八)贪心算法之简单贪心:从直觉到逻辑的实战指南
c++·算法·贪心算法·蓝桥杯·算法竞赛·acm/icpc·简单贪心
小欣加油1 小时前
leetcode 2536 子矩阵元素加1
数据结构·c++·算法·leetcode·矩阵
橘颂TA1 小时前
【剑斩OFFER】算法的暴力美学——二维前缀和
算法·c/c++·结构与算法
月半流苏1 小时前
Problem: lab-week10-exercise02 Building a Fiber Network
c++·算法·并查集
小龙报2 小时前
《VScode搭建教程(附安装包)--- 开启你的编程之旅》
c语言·c++·ide·vscode·单片机·物联网·编辑器
努力学算法的蒟蒻2 小时前
day14(11.14)——leetcode面试经典150
算法·leetcode