title: Daily practice (42): Excel sheet serial number
categories:[Swords offer]
tags:[Daily practice]
date: 2022/04/14
Daily practice (42): Excel sheet serial number
Gives you a string columnTitle representing the column name in the Excel table. Returns the column sequence number corresponding to the column name.
E.g:
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
hint:
1 <= columnTitle.length <= 7
columnTitle consists of uppercase English only
columnTitle is in range ["A", "FXSHRXW"]
Source: LeetCode
Link: https://leetcode-cn.com/problems/excel-sheet-column-number
Method 1: Base conversion (front to back)
Thought analysis
This question requires converting the column names in the Excel table to the corresponding column numbers. Since the column name of the Excel table consists of uppercase letters, there are 26 uppercase letters, so the column name
Indicates that the essence is 26 hexadecimal, and it is necessary to convert 26 hexadecimal to decimal.
Hexadecimal conversion to get the value according to the ASCII code.
int titleToNumber(string columnTitle) {
int ans = 0;
for (char c : columnTitle) {
int k = c - 'A' + 1;
ans = ans * 26 + k;
}
return ans;
}
Method 2: Base conversion (from back to front)
Thought analysis
Hexadecimal conversion to get the value according to the ASCII code.
int titleToNumber(string columnTitle) {
int ans = 0;
long multiple = 1;
int n = columnTitle.length() - 1;
for (int i = n; i >= 0; --i) {
int k = columnTitle[i] - 'A' + 1;
ans += k * multiple;
multiple *= 26;
}
return ans;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。