168. Excel Sheet Column Title
給定一個整數 columnNumber,返回它在 Excel 表格中對應的列標題。
例如:A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
範例 :
輸入:columnNumber = 1
輸出:"A"
Python
class Solution:
def convertToTitle(self, columnNumber: int) -> str:
result = []
while columnNumber > 0:
columnNumber -= 1
remainder = columnNumber % 26
result.append(chr(65 + remainder))
columnNumber //= 26
return ''.join(result[::-1])
16.58MB, 44ms
C++
class Solution {
public:
string convertToTitle(int columnNumber) {
string result;
while (columnNumber > 0) {
columnNumber--; // Convert to 0-indexed
int remainder = columnNumber % 26;
result += (char)(remainder + 'A');
columnNumber /= 26;
}
reverse(result.begin(), result.end());
return result;
}
};
7.01MB, 2ms
Javascript
/**
* @param {number} columnNumber
* @return {string}
*/
var convertToTitle = function(columnNumber) {
let result = "";
while (columnNumber > 0) {
columnNumber--; // Convert to 0-indexed
let remainder = columnNumber % 26;
result = String.fromCharCode(65 + remainder) + result;
columnNumber = Math.floor(columnNumber / 26);
}
return result;
};
48.88MB, 51ms