sicily 1298. 数制转换
这道题我这个菜鸟还是想了很久,也看过各位神牛的代码。有很多方法,没有去比较过它们的效率问题,只是选择了自己决定容易理解的方法来做。
需要声明的是,下面的代码不是本人所写,是“剽窃”大牛Dy.T的博客http://tuodeyi.blog.163.com/blog/static/17651458020113802141292/
自己只是加了一些注释
思路如下:
使用递归模拟平常取余的方法,首先求出的余数是最低位;关键在于对-2,-1,0,1,,2共5个余数的处理方法;若余数为2,由于题目规定
编码只有-1,0,1,故须将正常求得的余数2进行转换,即相当于把2编码为1,同时给高位进一位即可。对于其他的余数也类似
1 #include <iostream> 2 using namespace std ; 3 int src ; 4 void handle(int x) 5 { 6 if(x>0) 7 { 8 if(x%3==0) 9 { 10 handle(x/3) ; 11 cout << 0 ; //注意这里,因为前一个语句是使用递归函数,故其实这里的输出时低位 12 } 13 else if(x%3==1) 14 { 15 handle((x-1)/3) ; //为了取得当前的商,当做另一个新的数来处理 16 cout << 1 ; 17 } 18 else 19 { 20 handle((x+1)/3) ; 21 cout << '-' ; 22 } 23 } 24 25 26 else if(x<0) 27 { 28 if(-x%3==0) 29 { 30 handle(x/3) ; 31 cout << 0 ; 32 } 33 else if(-x%3 == 1) 34 { 35 handle((x+1)/3) ; 36 cout << '-' ; 37 } 38 else 39 { 40 handle((x-1)/3) ; 41 cout << 1 ; 42 } 43 } 44 } 45 46 int main() 47 { 48 while(cin >> src) 49 { 50 if(src==0)cout << 0 ; 51 else handle(src) ; 52 cout << endl; 53 } 54 return 0 ; 55 }