您的位置:首页 > 其它

UVA 11121 Base -2 (进制转换)

2015-02-13 19:56 351 查看
题目:http://uva.onlinejudge.org/external/111/11121.pdf

题意:给你一个数n,将n转换成-2进制。

分析:将n连续除以-2,然后把余数保存,最后倒着输出来就行了。注意余数为负数时,将余数加2,保证余数在0~1,然后n要加上1。

代码:

#include <iostream>
#include <cstdio>
#include <cmath>
#include <stack>
using namespace std;

int main()
{
	stack <int > st;
	int ncase;
	int x,i,r,t;
	scanf("%d",&ncase);
	for(i=1;i<=ncase;i++)
	{
		while(!st.empty()) st.pop();
		scanf("%d",&x);
		while(x)
		{
			r=x%-2;
			t=x/-2;
			if(r<0)
			{
				r+=2;
				t++;
			}
			st.push(r);
			x=t;
		}
		printf("Case #%d: ",i);
		if(st.empty())
		{
			printf("0\n");
			continue;
		}
		while(!st.empty())
		{
			printf("%d",st.top());
			st.pop();
		}
		printf("\n");
	}
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: