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