sicily 1298 数制转换

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

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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值