title: Daily practice (41): Excel table column name
categories:[Swords offer]
tags:[Daily practice]
date: 2022/04/13
Daily practice (41): Excel table column names
Given an integer columnNumber, return its corresponding column name in the Excel table.
E.g:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
Example 1:
Input: columnNumber = 1
Output: "A"
Example 2:
Input: columnNumber = 28
Output: "AB"
Example 3:
Input: columnNumber = 701
Output: "ZY"
Example 4:
Input: columnNumber = 2147483647
Output: "FXSHRXW"
hint:
1 <= columnNumber <= 231 - 1
Source: LeetCode
Link: https://leetcode-cn.com/problems/excel-sheet-column-title
Method 1: Hexadecimal conversion from 1
Thought analysis
The normal 26 hexadecimal display number should be 0-25, and this question is 1-26, then subtract one before processing each digit, which can become a normal hexadecimal conversion operation.
string convertToTitle(int columnNumber) {
string ans;
do {
columnNumber--;
ans = char(columnNumber % 26 + 'A') + ans;//得到字符列名称
columnNumber /= 26;
} while(columnNumber > 0);
return ans;
}
Method 2: Remainder + Invert
Thought analysis
When the remainder is 0, we can't take @ but should take Z
string convertToTitle(int columnNumber) {
string ans;
while (columnNumber) {
int remainder = columnNumber % 26;
if (remainder == 0) { //如果余数是0,就像上一位借个1(26)出来,让余数强行等于26
remainder = 26;
columnNumber -= 26;
}
ans.push_back(remainder + 'A' - 1);
columnNumber /= 26;
}
reverse(ans.begin(), ans.end());//字符串倒序
return ans;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。