168.Excel Sheet Column Title
Given an integer columnNumber
, return its corresponding column title as it appears in an Excel sheet.
For example:
1 2 3 4 5 6 7 8
| A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ...
|
Example 1:
1 2
| Input: columnNumber = 1 Output: "A"
|
Example 2:
1 2
| Input: columnNumber = 28 Output: "AB"
|
Example 3:
1 2
| Input: columnNumber = 701 Output: "ZY"
|
时间复杂度:O(log26columnNumber)
空间复杂度:O(1)
1 2 3 4 5 6 7 8 9 10 11 12
| class Solution { public: string convertToTitle(int columnNumber) { string ans_s = ""; while (columnNumber != 0) { ans_s += (columnNumber - 1) % 26 + 'A'; columnNumber = (columnNumber - (columnNumber - 1) % 26 - 1) / 26; } reverse(ans_s.begin(), ans_s.end()); return ans_s; } };
|
代码优化:
时间复杂度:O(log26columnNumber)
空间复杂度:O(1)
1 2 3 4 5 6 7 8 9 10 11 12 13
| class Solution { public: string convertToTitle(int columnNumber) { string ans; while (columnNumber > 0) { --columnNumber; ans += columnNumber % 26 + 'A'; columnNumber /= 26; } reverse(ans.begin(), ans.end()); return ans; } };
|