File tree Expand file tree Collapse file tree 1 file changed +72
-0
lines changed
src/excelSheetColumnTitle Expand file tree Collapse file tree 1 file changed +72
-0
lines changed Original file line number Diff line number Diff line change 1+ // Source : https://oj.leetcode.com/problems/excel-sheet-column-title/
2+ // Author : Hao Chen
3+ // Date : 2014-12-25
4+
5+ /* *********************************************************************************
6+ *
7+ * Given a positive integer, return its corresponding column title as appear in an Excel sheet.
8+ *
9+ * For example:
10+ *
11+ * 1 -> A
12+ * 2 -> B
13+ * 3 -> C
14+ * ...
15+ * 26 -> Z
16+ * 27 -> AA
17+ * 28 -> AB
18+ *
19+ * Credits:Special thanks to @ifanchu for adding this problem and creating all test cases.
20+ *
21+ **********************************************************************************/
22+
23+ #include < stdio.h>
24+ #include < stdlib.h>
25+ #include < iostream>
26+ #include < string>
27+ using namespace std ;
28+
29+
30+ string base26_int2str (long long n) {
31+ string ret;
32+ while (n>0 ){
33+ char ch = ' A' + (n-1 )%26 ;
34+ ret.insert (ret.begin (), ch );
35+ n -= (n-1 )%26 ;
36+ n /= 26 ;
37+ }
38+ return ret;
39+ }
40+
41+ long long base26_str2int (string& s){
42+ long long ret=0 ;
43+ for (int i=0 ; i<s.size (); i++){
44+ int n = s[i] - ' A' + 1 ;
45+ ret = ret*26 + n;
46+ }
47+ return ret;
48+ }
49+
50+
51+ string convertToTitle (int n) {
52+ return base26_int2str (n);
53+ }
54+
55+ int main (int argc, char **argv)
56+ {
57+ long long n = 27 ;
58+ if (argc>1 ){
59+ n = atoll (argv[1 ]);
60+ }
61+ string ns = base26_int2str (n);
62+ n = base26_str2int (ns);
63+
64+ cout << n << " = " << ns << endl;
65+
66+
67+ ns = " ABCDEFG" ;
68+ if (argc>2 ){
69+ ns = argv[2 ];
70+ }
71+ cout << ns << " = " << base26_str2int (ns) << endl;
72+ }
You can’t perform that action at this time.
0 commit comments