-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0168-Excel_Sheet_Column_Title.cpp
More file actions
92 lines (83 loc) · 1.88 KB
/
0168-Excel_Sheet_Column_Title.cpp
File metadata and controls
92 lines (83 loc) · 1.88 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/*******************************************************************************
* 0168-Excel_Sheet_Column_Title.cpp
* Billy.Ljm
* 22 August 2023
*
* =======
* Problem
* =======
* https://leetcode.com/problems/excel-sheet-column-title/
*
* Given an integer columnNumber, return its corresponding column title as it
* appears in an Excel sheet.
*
* For example:
* A -> 1
* B -> 2
* C -> 3
* ...
* Z -> 26
* AA -> 27
* AB -> 28
* ...
*
* ===========
* My Approach
* ===========
* This is identical to decimal to binary conversion.
*
* This has a time complexity of O(log n), and a space complexity of O(log n),
* where n is the column number.
******************************************************************************/
#include <iostream>
#include <vector>
using namespace std;
/**
* << operator for vectors
*/
template <typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
os << "[";
for (const auto elem : v) {
os << elem << ",";
}
if (v.size() > 0) os << "\b";
os << "]";
return os;
}
/**
* Solution
*/
class Solution {
public:
string convertToTitle(int columnNumber) {
string out = "";
while (columnNumber > 0) {
columnNumber--;
out = out + (char)('A' + (columnNumber % 26));
columnNumber = columnNumber / 26;
}
reverse(out.begin(), out.end());
return out;
}
};
/**
* Test cases
*/
int main(void) {
Solution sol;
int columnNumber;
// test case 1
columnNumber = 1;
std::cout << "convertToTitle(" << columnNumber << ") = ";
std::cout << sol.convertToTitle(columnNumber) << std::endl;
// test case 2
columnNumber = 28;
std::cout << "convertToTitle(" << columnNumber << ") = ";
std::cout << sol.convertToTitle(columnNumber) << std::endl;
// test case 3
columnNumber = 701;
std::cout << "convertToTitle(" << columnNumber << ") = ";
std::cout << sol.convertToTitle(columnNumber) << std::endl;
return 0;
}