forked from weiliu89/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
excelSheetColumnTitle.cpp
72 lines (61 loc) · 1.47 KB
/
excelSheetColumnTitle.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
// Source : https://oj.leetcode.com/problems/excel-sheet-column-title/
// Author : Hao Chen
// Date : 2014-12-25
/**********************************************************************************
*
* 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
*
* Credits:Special thanks to @ifanchu 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 convertToTitle(int n) {
return base26_int2str(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;
}