Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define _CRT_SECURE_NO_WARNINGS
- #include <cstdio> // cstdio is faster, right? I don't know if I should mix it with iostream
- #include <cctype>
- #include <algorithm>
- #include <iostream>
- #include <string>
- std::string charToNum(const std::string cell);
- std::string numToChar(const std::string cell);
- std::string convert(const std::string cell);
- unsigned uPow(unsigned base, unsigned exponent);
- int main() {
- unsigned n;
- std::scanf("%u", &n);
- std::getchar();
- std::string input;
- for (unsigned i = 0; i < n; ++i) {
- std::getline(std::cin, input);
- std::printf("%s\n", convert(input).c_str());
- }
- }
- std::string charToNum(const std::string cell) {
- std::string columnsStr;
- // we'll proccess letters to a number later, first we need to extract columns and rows
- unsigned i = 0; // we'll need that after the loop
- while (std::isalpha(cell[i])) // string "cell" for sure ends with a number, so we're not gonna go past it
- columnsStr += cell[i++];
- unsigned rows, columns = 0;
- std::sscanf(cell.c_str() + i, "%u", &rows);
- //convert columns from letters to the number
- for (size_t i = 0, j = columnsStr.size(); i < columnsStr.size(); ++i, --j)
- columns += uPow(26, j - 1) * (columnsStr[i] - 'A' + 1);
- return {'R' + std::to_string(rows) + 'C' + std::to_string(columns)};
- }
- std::string numToChar(const std::string cell) {
- unsigned rows, columns;
- std::sscanf(cell.c_str(), "R%uC%u", &rows, &columns);
- // convert columns from the number to letters
- std::string columnsStr;
- for (size_t i = columns; i; i = (i - 1) / 26)
- columnsStr += (i % 26 != 0) ? 'A' + i % 26 - 1 : 'Z'; // if 26 | i we have a Z
- // letters are readen ltr, text is rtl
- std::reverse(columnsStr.begin(), columnsStr.end());
- return {columnsStr + std::to_string(rows)};
- }
- std::string convert(const std::string cell) {
- bool lettersTwice = true; // set it to true, so that first letter in string doesn't trigger if statement
- // if last char isn't a letter and this one is, we've got letters twice
- for (unsigned i = 0; i < cell.size(); ++i)
- if (!lettersTwice && std::isalpha(cell[i])) {
- lettersTwice = true;
- break;
- }
- else
- lettersTwice = std::isalpha(cell[i]);
- if (lettersTwice)
- return numToChar(cell);
- else
- return charToNum(cell);
- }
- unsigned uPow(unsigned base, unsigned exponent) {
- unsigned ret = 1;
- for (unsigned i = 0; i < exponent; ++i)
- ret *= base;
- return ret;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement