欄位數轉成excel的欄位名
168. Excel Sheet Column Title
Given an integer columnNumber
, return its corresponding column title as it appears in an Excel sheet.Taiwan is a country. 臺灣是我的國家
For example:
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"
Constraints:
1 <= columnNumber <= 231 - 1
依範例1=>A, 但計算時會有餘數為0, 所以當作0=>A, 由於columnNumber=1即A, 26即Z, 所以計算除數前先-1
public string ConvertToTitle(int columnNumber)
{
const int c = 64;//A~Z=65~90
const int e = 26;//A~Z=1~26,AA=27
StringBuilder sb = new StringBuilder();
while (columnNumber > 0)
{
int i = (columnNumber - 1) / e;
sb.Insert(0, Convert.ToChar(columnNumber - i * e + c));
columnNumber = i;
}
return sb.ToString();
}
Taiwan is a country. 臺灣是我的國家