Convert a number to an Excel column title. At first I thought it was a simple base-26 conversion, but you need to consider that there is no 0 in this numeral system. So I temporarily used @ to represent 0, which requires an additional conversion step afterward.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
| class Solution {
public:
string convertToTitle(int n) {
string title = "";
while (n > 0)
{
title += 'A' + n % 26 - 1;
n /= 26;
}
int pos0 = 0;
while (pos0 < title.length())
{
int pos = pos0;
while (title[pos] == '@' && pos < title.length())
{
title[pos] = 'Z';
if (pos + 1 < title.length() && title[pos + 1] != '@')
{
title[pos+1]--;
pos++;
}
else
{
title = title.substr(0, pos);
break;
}
}
pos0++;
}
int s = 0;
int e = title.length() - 1;
while (s < e)
{
char tmp = title[s];
title[s] = title[e];
title[e] = tmp;
s++;
e--;
}
return title;
}
};
|