Description
{ 0-9,A-Z,a-z }
HINT: If you make a sequence of base conversions using the output of one conversion as the input to the next, when you get back to the original base, you should get the original number.
Input
Output
Sample Input
8 62 2 abcdefghiz 10 16 1234567890123456789012345678901234567890 16 35 3A0C92075C0DBF3B8ACBC5F96CE3F0AD2 35 23 333YMHOUE8JPLT7OX6K9FYCQ8A 23 49 946B9AA02MI37E3D3MMJ4G7BL2F05 49 61 1VbDkSIMJL3JjRgAdlUfcaWj 61 5 dl9MDSWqwHjDnToKcsWE1S 5 10 42104444441001414401221302402201233340311104212022133030
Sample Output
62 abcdefghiz 2 11011100000100010111110010010110011111001001100011010010001 10 1234567890123456789012345678901234567890 16 3A0C92075C0DBF3B8ACBC5F96CE3F0AD2 16 3A0C92075C0DBF3B8ACBC5F96CE3F0AD2 35 333YMHOUE8JPLT7OX6K9FYCQ8A 35 333YMHOUE8JPLT7OX6K9FYCQ8A 23 946B9AA02MI37E3D3MMJ4G7BL2F05 23 946B9AA02MI37E3D3MMJ4G7BL2F05 49 1VbDkSIMJL3JjRgAdlUfcaWj 49 1VbDkSIMJL3JjRgAdlUfcaWj 61 dl9MDSWqwHjDnToKcsWE1S 61 dl9MDSWqwHjDnToKcsWE1S 5 42104444441001414401221302402201233340311104212022133030 5 42104444441001414401221302402201233340311104212022133030 10 1234567890123456789012345678901234567890
解題思路
進制轉換,高精度的除法,怎麼記錄商,怎麼記錄餘數,都是要注意的。
剛看到題目的時候感覺這麼多字符轉換,好麻煩,想想還是好方法最重要
AC代碼
#include<stdio.h>
#include<string.h>
#define MAXNSIZE 1005
char str[MAXNSIZE];
int start[MAXNSIZE], ans[MAXNSIZE], rest[MAXNSIZE];
int oldBase, newBase; //原來的進制, 現在的進制
int getNum(char ch) //字符 轉換 數值
{
if(ch >= '0' && ch <= '9') return ch - '0';
if(ch >= 'A' && ch <= 'Z') return ch - 'A' + 10;
return ch - 'a' + 36;
}
char getChar(int i) //數值 轉換 字符
{
if(i >= 0 && i <= 9) return '0' + i;
if(i >= 10 && i <= 35) return 'A' + i - 10;
return 'a' + i - 36;
}
void change() //字符串 轉換成 整形數組
{
start[0] = strlen(str);
for(int i = 1; i <= start[0]; i++)
start[i] = getNum(str[i-1]);
}
void solve() //rest[0],start[0],ans[0],記錄各數組的長度
{
memset(rest, 0, sizeof(rest));
int y, i, j;
while(start[0] >= 1)
{
y = 0; i = 1;
ans[0] = start[0];
while(i <= start[0])
{
y = y * oldBase + start[i]; //進制轉換,邊乘邊除求餘,ans[]記錄商,餘數存入rest[]數組中
ans[i++] = y / newBase;
y %= newBase;
}
rest[ ++rest[0] ] = y; //rest[]是倒序的
i = 1;
while(i <= ans[0] && ans[i] == 0) //去除前導0
i++;
memset(start, 0, sizeof(start));
for(j = i; j <= ans[0]; j++)
start[ ++start[0] ] = ans[j]; //start[]賦新值,ans[]中的商
memset(ans, 0, sizeof(ans));
}
}
void output()
{
printf("%d %s\n", oldBase, str);
printf("%d ", newBase);
for(int i = rest[0]; i >= 1; i--)
printf("%c", getChar(rest[i]));
printf("\n\n");
}
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
scanf("%d %d %s", &oldBase, &newBase, str);
change();
solve();
output();
}
return 0;
}