LeetCode //C - 171. Excel Sheet Column Number

168. Excel Sheet Column Title

Given a string columnTitle that represents the column title as appears in an Excel sheet, return its corresponding column number.

For example:

A -> 1

B -> 2

C -> 3

...

Z -> 26

AA -> 27

.AB -> 28

...

Example 1:

Input: columnTitle = "A"
Output: 1

Example 2:

Input: columnTitle = "AB"
Output: 28

Example 3:

Input: columnTitle = "ZY"
Output: 701

Constraints:
  • 1 <= columnTitle.length <= 7
  • columnTitle consists only of uppercase English letters.
  • columnTitle is in the range ["A", "FXSHRXW"].

From: LeetCode

Link: 171. Excel Sheet Column Number


Solution:

Ideas:
  1. The function titleToNumber takes a string columnTitle as input.
  2. It initializes an integer result to 0.
  3. It iterates over each character in the string. For each character, it updates the result by multiplying the current result by 26 (since there are 26 letters in the alphabet) and adding the position of the current character in the alphabet (calculated as *columnTitle - 'A' + 1).
  4. The function returns the final result, which is the corresponding column number.
Code:
c 复制代码
int titleToNumber(char* columnTitle) {
    int result = 0;
    while (*columnTitle) {
        result = result * 26 + (*columnTitle - 'A' + 1);
        columnTitle++;
    }
    return result;
}
相关推荐
IronMurphy8 小时前
【算法三十九】994. 腐烂的橘子
算法
Tomhex9 小时前
C语言内存安全防护指南
c语言
Ares-Wang9 小时前
算法》》旅行商问题 TSP、7座桥问题 哈密顿回路 深度优先 和 宽度优先
算法·深度优先·宽度优先
Liqiuyue9 小时前
Transformer:现代AI革命背后的核心模型
人工智能·算法·机器学习
WolfGang0073219 小时前
代码随想录算法训练营 Day34 | 动态规划 part07
算法·动态规划
Kk.080210 小时前
Linux(十一)fork实例练习、文件操作示例及相关面试题目分享
linux·运维·算法
潇冉沐晴10 小时前
2026CCCC第三次模拟赛 部分题解
算法
230万光年的思念11 小时前
zerotier连不上的问题
c语言
WolfGang00732111 小时前
代码随想录算法训练营 Day32 | 动态规划 part05
算法·动态规划