NOIP2000 进制转换

传送门

这题以前搞过,不过总是没懂。今天偶然看到以后思考了一下明白了。

可能这道题提醒人的重点在于,任何一个数也可以表示成为负进制的幂次方形式。这样的话,回想起正数是怎么表示的,我们仿照正数的做法,只要进行短除即可。不过因为短除之后你的结果不能是负数,所以如果出现了负数,你就要在原数“借1”(不过因为是负进制,所以实际表现形式是+1),然后这位余数减去base即可。

之后就可以A啦。

看一下代码。

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<iostream>
#include<set>
#include<queue>
#define rep(i,a,n) for(int i = a;i <= n;i++)
#define per(i,n,a) for(int i = n;i >= a;i--)
#define pb push_back
#define enter putchar('\n')

using namespace std;
typedef long long ll;
const int M = 1000005;

ll read()
{
   ll ans = 0,op = 1;
   char ch = getchar();
   while(ch < '0' || ch > '9')
   {
      if(ch == '-') op = -1;
      ch = getchar();
   }
   while(ch >= '0' && ch <= '9')
   {
      ans *= 10;
      ans += ch - '0';
      ch = getchar();
   }
   return ans * op;
}

int n,base,p,a[100],cnt;

int main()
{
   n = read(),base = read(),p = n;
   while(p)
   {
      a[++cnt] = p % base,p /= base;
      if(a[cnt] < 0) a[cnt] -= base,p++;
   }
   printf("%d=",n);
   per(i,cnt,1)
   {
      if(a[i] >= 10) printf("%c",a[i] - 10 + 'A');
      else printf("%d",a[i]);
   }
   printf("(base%d)\n",base);
   return 0;
}

猜你喜欢

转载自www.cnblogs.com/captain1/p/9930757.html
今日推荐