这里其实想清楚是不难的。因为是规律题,所以可以列举一些数据,分正数和负数,然后找出规律,这题的规律还好找。
如
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++;
}
else
ans[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;
}