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;
}
相关推荐
CHANG_THE_WORLD2 小时前
金字塔降低采样
算法·金字塔采样
我爱学嵌入式2 小时前
C语言第 9 天学习笔记:数组(二维数组与字符数组)
c语言·笔记·学习
不知天地为何吴女士4 小时前
Day32| 509. 斐波那契数、70. 爬楼梯、746. 使用最小花费爬楼梯
算法
小坏坏的大世界4 小时前
C++ STL常用容器总结(vector, deque, list, map, set)
c++·算法
励志要当大牛的小白菜6 小时前
ART配对软件使用
开发语言·c++·qt·算法
qq_513970446 小时前
力扣 hot100 Day56
算法·leetcode
PAK向日葵7 小时前
【算法导论】如何攻克一道Hard难度的LeetCode题?以「寻找两个正序数组的中位数」为例
c++·算法·面试
爱装代码的小瓶子8 小时前
数据结构之队列(C语言)
c语言·开发语言·数据结构
爱喝矿泉水的猛男9 小时前
非定长滑动窗口(持续更新)
算法·leetcode·职场和发展
YuTaoShao9 小时前
【LeetCode 热题 100】131. 分割回文串——回溯
java·算法·leetcode·深度优先