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;
}
相关推荐
MATLAB代码顾问10 分钟前
MATLAB实现灰狼算法优化PID参数
算法·机器学习·matlab
Aurorar0rua36 分钟前
CS50 x 2024 Notes C - 09
c语言·开发语言·学习方法
承渊政道1 小时前
【动态规划算法】(完全背包问题从状态定义到空间优化)
数据结构·c++·学习·算法·leetcode·动态规划·哈希算法
超级大福宝1 小时前
【力扣48. 旋转图像】超好记忆版 + 口诀
c++·算法·leetcode
爱写代码的倒霉蛋1 小时前
2023年天梯赛L1-8
数据结构·算法
相醉为友2 小时前
040 Linux/裸机/RTOS 项目开发的跨平台兼容性——C语言静态接口抽象底层原理分析
linux·c语言·mcu
apollowing2 小时前
启发式算法WebApp实验室:从搜索策略到群体智能的能力进阶(上)
算法·启发式算法·web app
生物信息与育种2 小时前
黄三文院士领衔植物星球计划(PLANeT)发表Cell
人工智能·深度学习·算法·面试·transformer
aini_lovee2 小时前
WSN 四大经典无需测距定位算法
算法