进制转换
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
输入一个十进制数N,将它转换成R进制数输出。
输入
输入数据包含多个测试实例,每个测试实例包含两个整数N(32位整数)和R(2<=R<=16, R<>10)。
输出
为每个测试实例输出转换后的数,每个输出占一行。如果R大于10,则对应的数字规则参考16进制(比如,10用A表示,等等)。
示例输入
7 2 23 12 -4 3
示例输出
111 1B-11
法一:
#include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> #include <algorithm> using namespace std; void transform(int r, int n) { if (n == 0) return ; int b, c; b = n/r; c = n%r; transform(r, b); if (c >= 10) printf("%c", c+55); else printf("%d", c); } int main() { int n, m; while(~scanf("%d %d", &n, &m)) { if (n == 0) printf("0"); else if (n < 0) { printf("-"); transform(m, -n); } else transform(m, n); printf("\n"); } return 0; }
法二:
#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <cstdlib> #include <algorithm> using namespace std; char s[16]= {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; int main() { int n, r; int y[1000]; while(~scanf("%d %d", &n, &r)) { if(n == 0) printf("0\n"); else { int x = n, top = 0; while(x) { y[top]=x%r; x = x/r; top++; } if(n < 0) { printf("-"); while(top--) { int a = fabs(y[top]); printf("%c",s[a]); } } else { while(top--) printf("%c", s[y[top]]); } printf("\n"); } } return 0; }
#include <iostream> #include <cstdio> #include <cstdlib> #include <cmath> #include <cstring> #include <algorithm> #define stackmax 10000 //栈的初始空间存储分配量 #define stacknum 10000 //存储空间每次增加的分量 using namespace std; typedef char elemtype; typedef struct { elemtype *top; elemtype *base; int stacksize; } Qstack; //构建一个空栈 int Initstack(Qstack &s) { s.base = (elemtype *)malloc(stackmax*sizeof(elemtype)); if( !s.base ) exit(0); s.top = s.base; s.stacksize = stackmax; return 0; } //创建一个栈 int Pushstack(Qstack &s, char e) { if(s.top - s.base >= s.stacksize)//栈满, 追加存储空间 { s.base = (elemtype *)realloc(s.base, (s.stacksize+stacknum)*sizeof(elemtype)); if(!s.base) { exit(0); } s.top = s.base+s.stacksize; s.stacksize += stacknum; } /*for(int i = 0, i < n; i++) { scanf("%d", &e);//给栈赋值 *s.top++ = e; }*/ *s.top++ = e; return 0; } //出栈,输出栈里元素 int Putstack(Qstack &s, int f) { if(f != 0) printf("-"); while(s.top > s.base) { printf("%c", *(s.top-1)); s.top--; } printf("\n"); return 0; } int main() { int n, r, t; char e; Qstack s;//定义一个栈 while(~scanf("%d %d", &n, &r)) { int f=0; if(n == 0) { printf("0\n"); } else { if(n < 0) { n = -n; f = 1; } Initstack(s);//初始化栈 while(n) { t = n%r; if(t >= 10) e = t - 10 + 'A'; else e = t + '0'; Pushstack(s, e); n = n/r; } Putstack(s, f); } } return 0; }