进制转换 分类: 栈和队列 2015-06-09 10:23 12人阅读 评论(0) 收藏

进制转换

TimeLimit: 1000ms Memory limit: 65536K

题目描述

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

输入

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

输出

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

示例输入

72

2312

-43

示例输出

111

1B

-11

//模拟栈
#include <map>
#include <set>
#include <cmath>
#include <stack>
#include <queue>
#include <cstdio>
#include <cctype>
#include <vector>
#include <string>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#define RR freopen("input.txt","r",stdin)
#define WW freopen("output.txt","w",stdout)
#define INF 0x3f3f3f3f
using namespace std;
struct node
{
    char data;
    node *next;
};
int main()
{
    int n,m;
    node *head,*p;
    head=new node;
    while(~scanf("%d %d",&n,&m))
    {
        if(n==0)//注意零
        {
            cout<<0<<endl;
        }
        else
        {
            if(n<0)
            {
                cout<<'-';
                n=-n;
            }
            int ans;
            head->next=NULL;
            while(n)
            {
                p=new node;
                ans=n%m;
                if(ans>=0&&ans<=9)
                {
                    p->data=ans+'0';
                }
                else
                {
                    p->data=ans-10+'A';
                }
                p->next=head->next;
                head->next=p;
                n/=m;
            }
            p=head->next;
            while(p)
            {
                cout<<p->data;
                p=p->next;
            }
            cout<<endl;
        }
    }
    return 0;
}

STL 
#include <map>
#include <set>
#include <cmath>
#include <stack>
#include <queue>
#include <cstdio>
#include <cctype>
#include <vector>
#include <string>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#define RR freopen("input.txt","r",stdin)
#define WW freopen("output.txt","w",stdout)
#define INF 0x3f3f3f3f

using namespace std;

int main()
{
    int n,m;
    while(~scanf("%d %d",&n,&m))
    {
        if(n==0)
        {
            cout<<0<<endl;
            continue;
        }
        if(n<0)
        {
            cout<<'-';
            n=-n;
        }
        stack<char>B;
        int ans;
        while(n)
        {
            ans=n%m;
            if(ans>=0&&ans<=9)
            {
                B.push(ans+'0');
            }
            else
            {
                B.push(ans-10+'A');
            }
            n/=m;
        }
        while(!B.empty())
        {
            cout<<B.top();
            B.pop();
        }
        cout<<endl;
    }
    return 0;
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

原文地址:https://www.cnblogs.com/juechen/p/4722053.html