sicily 1298. 数制转换

#include<iostream>
using namespace std;
int res[1000];
int main()
{
int n;
while(cin>>n)
{
if(n==0)
{
cout
<<"0\n";
continue;
}
int m,r=0;
while(n!=0)
{
if(n>0)
{
if(n%3!=2)
{
res[r
++]=n%3;
n
/=3;
}
else //比如n=5, 应该将n看作是 3*2+(-1)
{
res[r
++]=-1;
n
=n/3+1;
}
}
else
{
m
=-n;
if(m%3==0)
{
res[r
++]=0;
n
/=3;
}
else if(m%3==1) //比如 n=-4,看作是 -4=3*-1+(-1)
{
res[r
++]=-1;
n
/=3;
}
else //比如 n=-5,看作是 -5=3*-2+(1)
{
res[r
++]=1;
n
=n/3-1;
}
}
}
for(int i=r-1;i>=0;--i)
if(res[i]==-1)
cout
<<"-";
else
cout
<<res[i];
cout
<<endl;
}
return 0;
}

  

posted on 2011-07-05 02:40  sysu_mjc  阅读(212)  评论(0编辑  收藏  举报

导航