hdu 2031 进制转换

来源:互联网 发布:二叉树层序遍历算法 编辑:程序博客网 时间:2024/06/16 04:28

题目来源:http://acm.hdu.edu.cn/showproblem.php?pid=2031

进制转换

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 28137    Accepted Submission(s): 15559


Problem Description
输入一个十进制数N,将它转换成R进制数输出。
 

Input
输入数据包含多个测试实例,每个测试实例包含两个整数N(32位整数)和R(2<=R<=16, R<>10)。
 

Output
为每个测试实例输出转换后的数,每个输出占一行。如果R大于10,则对应的数字规则参考16进制(比如,10用A表示,等等)。
 

Sample Input
7 223 12-4 3
 

Sample Output
1111B-11
 

Author
lcy
 

Source
C语言程序设计练习(五)
 

Recommend
lcy   |   We have carefully selected several similar problems for you:  1020 2090 1008 1108 2096 
 

   本题是一道很好的题目,如果学过数据结构,可以利用栈来解决,由于进制转换以及输出顺序,恰好和进出栈相符合,可以来代替递归!

   如果没有接触过数据结构,自然可以可以利用递归来解决。

非递归:

#include <iostream>#include <cstdio>#include <cstring>#include <stack>using namespace std;void Change_Num(int n, int r)//非递归{    stack <char> S;    while(!S.empty())        S.pop();    while(n)    {        S.push( n%r > 9 ? (n%r - 10 + 'A') : (n%r+'0') );//基数大于10要换成字母形式        n /= r;    }    while(!S.empty())    {        printf("%c", S.top());        S.pop();    }    return ;}int main(){    int N, R;    while(~scanf("%d %d", &N, &R))    {        if(N == 0)            printf("0");        if(N < 0)        {            printf("-");            N = -N;            Change_Num(N, R);        }        else            Change_Num(N, R);        printf("\n");    }    return 0;}

递归:

#include <iostream>#include <cstdio>#include <cstring>#include <stack>using namespace std;void Change_Num(int n, int r)//递归{    if(n == 0)        return ;    Change_Num(n/r, r);    char iNum = n%r > 9 ? (n%r - 10 + 'A') : (n%r +'0');    printf("%c", iNum);}int main(){    int N, R;    while(~scanf("%d %d", &N, &R))    {        if(N == 0)            printf("0");        if(N < 0)        {            printf("-");            N = -N;            Change_Num(N, R);        }        else            Change_Num(N, R);        printf("\n");    }    return 0;}



0 0
原创粉丝点击