Leetcode/cpp/168.cpp
2024-06-21 01:36:27 +01:00

39 lines
1.0 KiB
C++

#include <algorithm>
#include <array>
#include <cmath>
#include <iostream>
#include <string>
class Solution {
private:
std::array<char, 26> alphabet = {'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', 'Z'};
public:
std::string convertToTitle(int columnNumber) {
long power = 1;
short length = 0;
while (columnNumber >= power) {
columnNumber -= power;
power *= 26;
length++;
}
std::string out;
for (; length > 0; length--) {
int remainder = columnNumber % 26;
columnNumber = columnNumber / 26;
char corresponding_char = alphabet.at(remainder);
out.push_back(corresponding_char);
}
std::reverse(out.begin(), out.end());
return out;
}
};
int main() {
Solution sol;
for (int i = 1; i < 26*10; i++) {
std::cout << i << " -> " << sol.convertToTitle(i) << '\n';
}
}