LeetCode 168 Excel Sheet Column Title (Excel Column to table Title)
Translation
Given a positive integer, return it as the correct column title in the Excel table. Example: 1-> A 2-> B 3-> C... 26-> Z 27-> AA 28-> AB
Original
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
Analysis
I seldom use Excel, so I don't fully understand the meaning of the question. I will first look at other people's solutions.
class Solution {public: string convertToTitle(int n) { if (n<=0) return ""; if (n<=26) return string(1, 'A' + n - 1); return convertToTitle( n%26 ? n/26 : n/26-1 ) + convertToTitle( n%26 ? n%26 : 26 ); }};
Then we tried it in. Finally, I know what the question means ......
1 ... A*******26 ... Z27 ... AA*******52 ... AZ53 ... BA*******702 ... ZZ703 ... AAA
The recursion of the great god is actually 666, and the three-object operator is also used properly, so I have to admire it!
The above is
'A' + n - 1
Then I wrote the following code:
#include
using namespace std;string convertToTitle(int n) { string title; while (n > 0) { title = (char)('A' + (--n) % 26) + title; n /= 26; } return title;}int main() { cout << convertToTitle(702); return 0;}
Core code
title = (char)('A' + (--n) % 26) + title;
The solution is that it is used in habits
string title;title += "X";
This is all appended to the end. It may not be a habit to append the above, but it is no problem.
Because there is A starting A in it, so when we add it later, we need to reduce n by 1 at the beginning. Each time the last character is obtained, that is, every time a 26 character is removed, it is treated as a 26-digit system. In fact, it is consistent with the decimal system.
Code
class Solution {public: string convertToTitle(int n) { string res; while (n > 0) { res = (char)('A' + (--n) % 26) + res; n /= 26; } return res; }};