sundeepblue
4/12/2014 - 4:16 PM

convert excel column string to number, say, "AA" to 27.

convert excel column string to number, say, "AA" to 27.

int get_excel_column_index(const string& s) {
    if(s.empty()) return -1;
    int res = 0;
    for(char c : s) {
        res = 26 * res + c - 'A' + 1;      // gist, should use = not +=
    }
    return res;
}

// convert index to string
// eg: 1 --> A, 27 --> AA
string convert_excel_column(int n) {
    string res;
    while(n > 0) {
        n--;                        // gist, n-- first, then the n%26 and n/26 is meaningful.
        res = n % 26 + 'A' + res;
        n /= 26;
    }
    return res;
}