Post date: Aug 03, 2013 10:10:21 AM
Problem
Excel columns are labelled alphabetically in length-lexicographic order, i.e., A, B, C, ..., Z, AA, AB, ....
Given the 1-based numeric index of a column, return the corresponding label.
Example 1:
1
Output 1:
A
Example 2:
54
Output 2:
BB
Solution
/*
============================================================================
Author : James Chen
Email : a.james.chen@gmail.com
Description : Find the label in Excel
Created Date : 04-August-2013
Last Modified :
===========================================================================
*/
#include <iostream>
#include <iomanip>
#include <string>
#include <list>
#include <cassert>
using namespace std;
string FindLabel(int index)
{
assert(index > 0);
list<char> label;
while(index > 0)
{
front_inserter(label) = (index - 1) % 26 + 'A';
index = (index - 1) / 26;
}
return string(label.begin(), label.end());
}
void DoTest(int index)
{
assert(index > 0);
cout << "The index = " << index << endl;
cout << "The label = " << FindLabel(index) << endl;
cout << "------------------------------" << endl;
}
int main(int argc, char* argv[])
{
DoTest(1);
DoTest(26);
DoTest(27);
DoTest(53);
DoTest(54);
DoTest(26 * 26);
DoTest(26 * 26 * 26);
return 0;
}
Ouput
The index = 1
The label = A
------------------------------
The index = 26
The label = Z
------------------------------
The index = 27
The label = AA
------------------------------
The index = 53
The label = BA
------------------------------
The index = 54
The label = BB
------------------------------
The index = 676
The label = YZ
------------------------------
The index = 17576
The label = YYZ
------------------------------
Press any key to continue . . .