0%

excel-sheet-column-title

Excel Sheet Column Title – LeetCode 168

Problem

Description

Given a positive integer, return its corresponding column title as appear in an Excel sheet.

Example

1 -> A
2 -> B
3 -> C

26 -> Z
27 -> AA
28 -> AB

Answer

Original

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
string convertToTitle(int n) {
string result;
string alpha = "ZABCDEFGHIJKLMNOPQRSTUVWXY";
while(n > 26){
result = alpha[n % 26] + result;
n -= n % 26? n % 26: 26;
n /= 26;
}
result = alpha[n % 26] + result;
return result;
}
};

思路

简单的26进制转化,麻烦在于不已0为起始,所以要注意alpha的构造。时间复杂度$O(n)$,空间复杂度$O(1)$。
耗时$0$ ms,排名$84.25\%$

Better

思路

近似的思路,简洁的写法。时间复杂度$O(n)$,空间复杂度$O(1)$。
耗时$0$ ms,排名$84.25\%$

Code

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
string convertToTitle(int n) {
string ans;
while (n) {
ans = char ((n - 1) % 26 + 'A') + ans;
n = (n - 1) / 26;
}
return ans;
}
};