結果

問題 No.782 マイナス進数
ユーザー しらっ亭
提出日時 2017-05-13 00:29:56
言語 C++11(廃止可能性あり)
(gcc 13.3.0)
結果
AC  
実行時間 21 ms / 2,000 ms
コード長 977 bytes
コンパイル時間 1,261 ms
コンパイル使用メモリ 61,720 KB
実行使用メモリ 5,376 KB
最終ジャッジ日時 2024-09-15 10:49:44
合計ジャッジ時間 3,871 ms
ジャッジサーバーID
(参考情報)
judge4 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 36
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <vector>
#include <algorithm>
#include <cassert>

using namespace std;

void verify(const string &ans, int n, int b) {
  int m = (int) ans.size();

  long long v = 0;
  for (int i = 0; i < m; i++) {
    int d = ans[i] - '0';
    assert(d >= 0);
    assert(d < -b);
    v *= b;
    v += d;
  }
  assert(v == n);
  assert(n == 0 || ans[0] != '0');
}

string solve(int n, int b) {
  string ans;
  while (n) {
    int m = n % b;
    n /= b;
    if (m < 0) {
      m -= b;
      n++;
    }
    ans += '0' + m;
  }
  reverse(ans.begin(), ans.end());

  if (ans == "") ans += '0';
  return ans;
}

int main() {
  cin.tie(nullptr);
  ios::sync_with_stdio(false);

  int t, b, n;
  
  cin >> t >> b;

  assert(t >= 1);
  assert(t <= 100000);
  assert(b >= -10);
  assert(b <= -2);

  while (t--) {
    cin >> n;
    assert(n >= 0);
    assert(n <= 1000000000);
    string ans = solve(n, b);
    cout << ans << endl;
    verify(ans, n, b);
  }
  return 0;
}
0