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