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;
}
相关推荐
失落的香蕉5 分钟前
C语言串讲-2之指针和结构体
java·c语言·开发语言
ChoSeitaku2 小时前
链表循环及差集相关算法题|判断循环双链表是否对称|两循环单链表合并成循环链表|使双向循环链表有序|单循环链表改双向循环链表|两链表的差集(C)
c语言·算法·链表
DdddJMs__1352 小时前
C语言 | Leetcode C语言题解之第557题反转字符串中的单词III
c语言·leetcode·题解
Fuxiao___3 小时前
不使用递归的决策树生成算法
算法
我爱工作&工作love我3 小时前
1435:【例题3】曲线 一本通 代替三分
c++·算法
娃娃丢没有坏心思3 小时前
C++20 概念与约束(2)—— 初识概念与约束
c语言·c++·现代c++
白-胖-子3 小时前
【蓝桥等考C++真题】蓝桥杯等级考试C++组第13级L13真题原题(含答案)-统计数字
开发语言·c++·算法·蓝桥杯·等考·13级
workflower3 小时前
数据结构练习题和答案
数据结构·算法·链表·线性回归
好睡凯3 小时前
c++写一个死锁并且自己解锁
开发语言·c++·算法
Sunyanhui13 小时前
力扣 二叉树的直径-543
算法·leetcode·职场和发展