POJ

( ext{Solution})

主要是用这道题学习一下 (a) 进制转 (b) 进制的方法。

先给结论吧:

(a) 进制数不断除以 (b),将算出来的余数倒着排列就是对应的 (b) 进制数。

我们先说一下进制的本质:(a) 进制数就是给 (a) 的各个幂赋予一个系数,将对应的系数与幂相乘再相加,就是我们熟悉的十进制数。

再以 (2) 进制数为例:(10011) 中最后一个 (1) 表示其对应的十进制数被 (2^1) 取模等于 (1),倒数第二个 (1) 和倒数第一个 (1) 表示其对应的十进制数被 (2^2) 取模是 (3)

那么十进制转 (b) 进制就先取模一个 (b),得到最后一位的数......依此类推。

你现在可以看看我高精除的代码,其实也可以理解为维持 (a) 进制的形式,用十进制来计算。我们用每个幂的系数除以 (b),实际上就是整体除了 (b),然后将余数传递到下一位乘上 (a)

注意最后算出来的余数应该除以 (a),因为是由 (a^0) 位转化过来,实际上多乘了一个 (a)

( ext{Code})

#include <cstdio>

#define rep(i,_l,_r) for(register signed i=(_l),_end=(_r);i<=_end;++i)
#define fep(i,_l,_r) for(register signed i=(_l),_end=(_r);i>=_end;--i)
#define erep(i,u) for(signed i=head[u],v=to[i];i;i=nxt[i],v=to[i])
#define efep(i,u) for(signed i=Head[u],v=to[i];i;i=nxt[i],v=to[i])
#define print(x,y) write(x),putchar(y)

template <class T> inline T read(const T sample) {
    T x=0; int f=1; char s;
    while((s=getchar())>'9'||s<'0') if(s=='-') f=-1;
    while(s>='0'&&s<='9') x=(x<<1)+(x<<3)+(s^48),s=getchar();
    return x*f;
}
template <class T> inline void write(const T x) {
    if(x<0) return (void) (putchar('-'),write(-x));
    if(x>9) write(x/10);
    putchar(x%10^48);
}
template <class T> inline T Max(const T x,const T y) {if(x>y) return x; return y;}
template <class T> inline T Min(const T x,const T y) {if(x<y) return x; return y;}
template <class T> inline T fab(const T x) {return x>0?x:-x;}
template <class T> inline T gcd(const T x,const T y) {return y?gcd(y,x%y):x;}
template <class T> inline T lcm(const T x,const T y) {return x/gcd(x,y)*y;}
template <class T> inline T Swap(T &x,T &y) {x^=y^=x^=y;}

#include <cstring>

int toint(char x) {
	if(x>='0'&&x<='9') return x-'0';
	if(x>='A'&&x<='Z') return x-'A'+10;
	return x-'a'+36;
}

char tochar(int x) {
	if(x>=0&&x<=9) return x+'0';
	if(x>=10&&x<=35) return x-10+'A';
	return x-36+'a';
}

int n,m,tp;
char s[2000],sta[2000];
struct BigInt {
	int a[2000],base,len;
	
	void clear(int x,int l) {
		base=x; len=l;
		rep(i,1,len) a[i]=toint(s[len-i]);
	} 
	
	BigInt operator / (int x) {
		fep(i,len,1) a[i-1]+=a[i]%x*base,a[i]/=x;
		while(!a[len]&&len>1) --len;
		return *this;
	}
} x;

int main() {
	for(int t=read(9);t;--t) {
		n=read(9),m=read(9); tp=0;
		scanf("%s",s); int len=strlen(s);
		printf("%d %s
%d ",n,s,m);
		x.clear(n,len);
		while(!(!x.a[x.len]&&x.len==1)) {
			x=x/m;
			sta[++tp]=tochar(x.a[0]/n); x.a[0]=0;
		}
		if(tp==0) {puts("0"); putchar('
'); continue;}
		fep(i,tp,1) putchar(sta[i]); puts(""),puts("");
	}
	return 0;
}
原文地址:https://www.cnblogs.com/AWhiteWall/p/13777871.html