UVA 11121 Base -2

大意:将一个十进制的数转换成-2进制的数。

思路:

与转换为2进制类似,只不过迭代时,当n为负数的时候,n % base的值可能为-1,而我们不允许-1出现,则把-1替换为-1 -= base;而替换之后减少的那一部分的值需要在迭代的时候加回来。

有一个人讲的比较清楚:http://www.cnblogs.com/scau20110726/archive/2012/12/21/2828420.html

我们可以把这个推广到任意负数进制的转换。

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <string>
using namespace std;

const int base = -5;
const int MAXN = 100010;

int n;

int stack[MAXN];

void read_case()
{
	scanf("%d", &n);
}

void solve()
{
	read_case();
	if(!n) { printf("0\n"); return ; }
	int top = 0;
	while(n)
	{
		int t = n % base;
		n /= base;
		if(t < 0)
		{
			t -= base;
			n++;
		}
		stack[top++] = t;
	}
	while(top)
	{
		int t = stack[--top];
		printf("%d", t);
	}
	printf("\n");
}

int main()
{
	int T, times = 0;
	scanf("%d", &T);
	while(T--)
	{
		printf("Case #%d: ", ++times);
		solve();
	}
	return 0;
}

任意负数进制的转换:

void solve()
{
	read_case();
	if(!n) { printf("0\n"); return ; }
	int top = 0;
	while(n)
	{
		int t = n % base;
		n /= base;
		if(t < 0)
		{
			t -= base;
			n++;
		}
		stack[top++] = t;
	}
	while(top)
	{
		int t = stack[--top];
		printf("%d", t);
	}
	printf("\n");
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值