非負整数からエクセルの列表示への変換
非負整数が入力されたらエクセルの列の表示のような文字列を返すプログラムです.
#include <iostream> #include <string> using namespace std; string toAlphabet(unsigned int num) { const string chars("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); const int base = chars.size(); string s(""); int b = 0; ++num; while(true) { if(b != 0 && num <= 0) break; if(num != 0) --num; char c[2] = {chars.at(num % base), '\0'}; s.insert(0, c); ++b; num /= base; } return s; } int main(void) { int num; cin >> num; cout << toAlphabet(num) << endl; return 0; }
変数名が投げ遣りなのは仕様です.
一見ただの26進数に見えてそうでもないのが曲者です.1桁目はAは0ですが,2桁目以降はAは1を意味するので注意が必要です.
なんだかんだで文字列の扱いは苦手です.
追記:
引数に1足して26進数として扱ったほうが楽だったみたいです。