1118_数制转换

来源:互联网 发布:sql 循环insert 编辑:程序博客网 时间:2024/04/29 03:23
// 1118_数制转换.cpp : 定义控制台应用程序的入口点。////题目1118:数制转换//时间限制:1 秒内存限制:32 兆特殊判题:否提交:5215解决:2061//题目描述://求任意两个不同进制非负整数的转换(2进制~16进制),所给整数在long所能表达的范围之内。//不同进制的表示符号为(01...9,a,b,...,f)或者(01...9,A,B,...F)。//输入://输入只有一行,包含三个整数a,n,b。a表示其后的n 是a进制整数,b表示欲将a进制整数n转换成b进制整数。a,b是十进制整数,2 =< a,b <= 16。//数据可能存在包含前导零的情况。//输出://可能有多组测试数据,对于每组数据,输出包含一行,该行有一个整数为转换后的b进制数。输出时字母符号全部用大写表示,即(01...9,A,B,...F)。//样例输入://15 Aab3 7//样例输出://210306//提示://可以用字符串表示不同进制的整数。//来源://2008年北京大学图形实验室计算机研究生机试真题#include "stdafx.h"#include "stdio.h"#include "iostream"#include "string"#include "stack"#include "math.h"using namespace std;int main(){    int a,b;    string n;    while(cin>>a>>n>>b){        stack <char> s;        int i = 0;        int digit = 0;        while(i<n.length()){            if (isdigit(n[i])){                //digit += (n[i]-'0') * pow(a*1.0,(n.length()-1-i)*1.0);                digit = digit*a + (n[i]-'0');      //这种题目应该要从数字高位开始,比从低位开始方便            }            else if (isupper(n[i])){                digit = digit*a + (n[i]-'A'+10);            }            else if (islower(n[i])){                digit = digit*a + (n[i]-'a'+10);            }            i++;        }        int temp;        do         {            temp = digit%b;            if (temp>=10)                s.push(temp-10+'A');            else                s.push(temp+'0');            digit /= b;        } while (digit);        while(!s.empty()){            cout<<s.top();            s.pop();        }        cout<<endl;    }    return 0;}
0 0
原创粉丝点击