杭电2031进制转换

#include <cstdlib>
#include <iostream>
#include <math.h> 
using namespace std;

int main(int argc, char *argv[])
{
    int n,r;
    int Remainder[100]={0};
    while(cin>>n>>r)
    {
       int flag=0,t=n,k=0,Quotient=n;
       if(n>=0&&n<=r)
         cout<<n<<endl;
       if(n>r)
       {
         while(Quotient!=0)
         {
           Quotient=Quotient/r;
           k++;
         }
         Quotient=n;
         for(int i=0;i<k;i++)
         {
           Quotient=Quotient/r;
           if(Quotient>=0)
           {
             Remainder[i]=t%r; 
             t=t/r;
           }  
         }
         flag=1; 
       } 
       if(n<0)
       {  
         n=abs(n); 
         Quotient=n;
         t=n; 
         while(Quotient!=0)
         {
           Quotient=Quotient/r;
           k++;
         }
         Quotient=n;
         for(int i=0;i<k;i++)
         {
           Quotient=Quotient/r;
           if(Quotient>=0)
           {
             Remainder[i]=t%r; 
             t=t/r;
           }  
         }
         flag=0; 
       } 
       if(flag==1)
       {
         for(int i=k-1;i>=0;i--)
         {
           if(Remainder[i]==10)
             cout<<'A';
           if(Remainder[i]==11)
             cout<<'B';
           if(Remainder[i]==12)
             cout<<'C';
           if(Remainder[i]==13)
             cout<<'D';
           if(Remainder[i]==14)
             cout<<'E';
           if(Remainder[i]==15)
             cout<<'F';
           if(Remainder[i]>=0&&Remainder[i]<=9) 
             cout<<Remainder[i];     
         }
         cout<<endl;     
       } 
       if(flag==0)
       {
         cout<<"-" ; 
         for(int i=k-1;i>=0;i--)
         {
           if(Remainder[i]==10)
             cout<<'A';
           if(Remainder[i]==11)
             cout<<'B';
           if(Remainder[i]==12)
             cout<<'C';
           if(Remainder[i]==13)
             cout<<'D';
           if(Remainder[i]==14)
             cout<<'E';
           if(Remainder[i]==15)
             cout<<'F';
           if(Remainder[i]>=0&&Remainder[i]<=9) 
             cout<<Remainder[i];  
         } 
         cout<<endl; 
       } 
    }
    system("PAUSE");
    return EXIT_SUCCESS;
}

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2031
以上代码主要分为三个部分:1.n>r;2.0<n<=r;3.n<0;(n是十进制数,r是进制)

posted @ 2012-07-31 11:08  Marshalkk  阅读(406)  评论(0编辑  收藏  举报