-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path168. Excel Sheet Column Title.cpp
67 lines (57 loc) · 1.16 KB
/
168. Excel Sheet Column Title.cpp
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
Given a positive integer, return its corresponding column title as appear in an Excel sheet.
For example:
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB
...
Example 1:
Input: 1
Output: "A"
Example 2:
Input: 28
Output: "AB"
Example 3:
Input: 701
Output: "ZY"
The first solution using extra space, but fast
second one is slower but more space efficient
*/
class Solution {
public:
string convertToTitle(int n) {
vector<char> temp = {'Z', 'A', 'B', 'C', 'D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y'};
string res = "";
while ( n )
{
int mod = n % 26;
res = temp[mod] + res;
n = ( n - 1 ) / 26;
}
return res;
}
};
class Solution {
public:
string convertToTitle(int n) {
string res = "";
while ( n )
{
if ( !( n % 26 ) )
{
res = 'Z' + res;
}
else
{
char c = 'A' - 1 + n % 26;
res = c + res;
}
n = ( n - 1 ) / 26;
}
return res;
}
};