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;
}
相关推荐
随意起个昵称17 分钟前
【双指针】供暖器
算法
倒霉蛋小马20 分钟前
最小二乘法拟合直线,用线性回归法、梯度下降法实现
算法·最小二乘法·直线
codists44 分钟前
《算法导论(第4版)》阅读笔记:p82-p82
算法
埃菲尔铁塔_CV算法1 小时前
深度学习驱动下的目标检测技术:原理、算法与应用创新
深度学习·算法·目标检测
Dream it possible!1 小时前
LeetCode 热题 100_寻找重复数(100_287_中等_C++)(技巧)(暴力解法;哈希集合;二分查找)
c++·leetcode·哈希算法
float_com1 小时前
【背包dp-----分组背包】------(标准的分组背包【可以不装满的 最大价值】)
算法·动态规划
丶Darling.2 小时前
Day119 | 灵神 | 二叉树 | 二叉树的最近共公共祖先
数据结构·c++·算法·二叉树
思茂信息3 小时前
CST软件对OPERA&CST软件联合仿真汽车无线充电站对人体的影响
c语言·开发语言·人工智能·matlab·汽车·软件构建
L_cl3 小时前
【Python 算法零基础 3.递推】
算法
川川菜鸟3 小时前
2025长三角数学建模C题完整思路
c语言·开发语言·数学建模