2273:An Excel-lent Problem

keyword

n進表記 C++

概要

A,B,...,Z,AA,...,AZ,BA,...,ZZ,AAA,...という順に文字列を列挙する。n(<3*10^8)番目の文字列を求める問題。
26進数のように見えるけどちょっと違う(位取り記数法の0と1の役割がごちゃ混ぜになっているせい)。文字列を紙に縦に書いてみると解き方が見えてくる。
気分を変えてlong longのtypedefをint64にしてみた。

int main(){
    int64 row, column;
    char str[100];
    char colStr[10], tmp[10];
    while( gets(str) ){
        for(int i=0; str[i]; i++)if(!('0'<=str[i]&&str[i]<='9')){
            str[i] = ' ';
        }
        stringstream ss(str);
        ss >> row >> column;
        if(!(row||column)) break;
        int p = 0;
        column--;
        tmp[p++] = column%26 + 'A';
        column /= 26;
        while(--column >= 0){
            tmp[p++] = column%26 + 'A';
            column /= 26;
        }
        tmp[p] = '\0';

        for(int i=0; i<p; i++){
            colStr[i] = tmp[p-i-1];
        }
        colStr[p] = '\0';

        printf("%s%lld\n",colStr,row);
    }

    return 0;
}