"Leetcode conversion "Excel Sheet Column Title
@author: Wepon
@blog: http://blog.csdn.net/u012162613
1. Topics
Given a positive integer, return its corresponding column title as appear in an Excel sheet.
For example:
1, A 2, B 3, C ... AA, Z
2. AnalysisThe order in Excel is this: A~z,aa~zz,aaa~zzz ....The essence is a binary conversion, converting N to 26, and the conversion process is as follows (26 decimal numbers in parentheses):1-> (1)->a2-> (2)->b...26-> (Ten)->Z27-> (one)->aa28-> (->ab).....52-> (->az)53-> (+)->ba
It is therefore possible to convert N to a number of 26 binary representations, then to the number of each bit, according to the "1->a,2->b,3->c ...." 25->y,26->z "to transform. of course, according to the method of conversion (continuously except 26 to take the remainder), there can be no 26 of the remainder, such as:52-> (->az), the remainder is 0, this situation to be special treatment, very simple, as shown in the following code: 3. Code
string Converttotitle (int n) { string str; while (n) { int r=n%26; N=N/26; if (r==0) { //is an integer multiple of 26, the bit is set to Z,n minus 1 str+= ' Z '; n--; } else{ str+= (' A ' +r-1); } } Reverses string result; for (int i=str.size () -1;i>=0;i--) { result+=str[i]; } return result; }
"Leetcode conversion" Excel Sheet Column Title