sicily 1298 数制转换

来源:互联网 发布:linux常用哪些版本 编辑:程序博客网 时间:2024/05/20 07:36

这里其实想清楚是不难的。因为是规律题,所以可以列举一些数据,分正数和负数,然后找出规律,这题的规律还好找。

1 = 1, 2 = 1-, 3 = 10, 4 = 11,5 = 1--,6 = 1-0....

-1 = -,-2=-1, -3 = -0,-4 = --,-5 = -11,-6 = -10...

从上面已经可以看出正数和负数转换后的结果存在对称关系,即转换后的正数1对应负数的 - ,-对应1,0不变。所以只要知道正数怎么计算就可以了。

从2 = 1-可以知道,如果某个数模3余数是2,则结果应该为-,并且该数除3的商加1。如果余数是1和0则保持不变。可以看下5怎么算

5%3 = 2 ----output - ,5/3 + 1 = 2

2%3 = 2 ----output -,2%3 + 1 = 3

3%3 = 0 ----output 1,此时已经能够整除,结束循环。

这里有一点需要注意的就是只输入0的问题,我用一次wrong answer换来的。。。。0的情况直接输出就行了。


#include <cstdio>#include <iostream>using namespace std;int main(){//freopen("input.txt","r",stdin);long long n;while (cin >> n) {if (n == 0) {cout << 0 << endl;continue;}char ans[1000];int i = 0, tmp;bool f;f = false;   //标记是否为负数if (n < 0) {f = true;n = -n;}//获取进制转换结果。while (n) {tmp = n%3;n = n/3;if (tmp == 2) {ans[i++] = '-';n++;}elseans[i++] = tmp + '0';}//为负数的话,就对结果进行翻转1变-,-变1,0不变if (f) {for (int j = 0; j < i; j++)if (ans[j] == '-')ans[j] = '1';else if (ans[j] == '1')ans[j] = '-';}i--;while (i >= 0) {cout << ans[i];i--;}cout << endl;}return 0;}