N進数 7進数 変換 C++

ACコード

https://yukicoder.me/submissions/352443

Code

  • baseで割って余りを記録し、逆順に読む
  • ※バグあり
string change_base(ll a, ll base){
    if(a==0) return "0";
    stringstream ss;
    while(a){
        ll rest = a%base;
        ss << rest;
        a /= base;
    }
    string s = ss.str();
    reverse(ALL(s));
    return s;
}

類題

C - 異世界転生 https://atcoder.jp/contests/tkppc4-1/tasks/tkppc4_1_c

書き直し

  • baseが大きい時、restが2桁以上になるので上記だとバグる
  • (stringにするのがまずいので) 取り急ぎ、修正版
VI change_base(ll a, ll base){
    if(a==0) return {0};
    VI A;
    while(a){
        ll rest = a%base;
        A.push_back(rest);
        a /= base;
    }
    reverse(ALL(A));
    return A;
}

void change_base_test(){
  debug(change_base(100, 3)); // 100を3進数ベースにすると
  debug(change_base(100, 10)); // {1,0,0}
  debug(change_base(100, 11)); // {9,1}
  debug(change_base(100, 57)); // {1,43}
}

verified

類題