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;
}
相关推荐
ysa051030几秒前
动态规划-逆向
c++·笔记·算法
燃于AC之乐3 分钟前
我的算法修炼之路--7—— 手撕多重背包、贪心+差分,DFS,从数学建模到路径DP
c++·算法·数学建模·深度优先·动态规划(多重背包)·贪心 + 差分
海上Bruce7 分钟前
C primer plus (第六版)第十二章 编程练习第3题
c语言
chinesegf12 分钟前
文本嵌入模型的比较(一)
人工智能·算法·机器学习
SundayBear30 分钟前
零基础入门MQTT协议
c语言·单片机
我能坚持多久44 分钟前
D16—C语言内功之数据在内存中的存储
c语言·开发语言
We་ct1 小时前
LeetCode 6. Z 字形变换:两种解法深度解析与优化
前端·算法·leetcode·typescript
REDcker1 小时前
Redis容灾策略与哈希槽算法详解
redis·算法·哈希算法
福楠2 小时前
C++ STL | map、multimap
c语言·开发语言·数据结构·c++·算法
极客小云2 小时前
【基于 PyQt6 的红外与可见光图像配准工具开发实战】
c语言·python·yolo·目标检测