首页 > 编程语言 > 详细

【C语言】逆转二进制数的几种方法

时间:2014-12-28 19:35:12      阅读:300      评论:0      收藏:0      [点我收藏+]

比如输入10(1010)

输出 5(101)

代码有三种:

最笨的方法循环:
int fuc(int x)
{
	int count=0;
	int num=0;
	int n=x;
	while(n!=0)
	{
		n/=2;
		count++;
	}
	while(x!=0)
	{
		if(x%2==1)
		num+=(int)pow(2,count-1);
		x/=2;
		count--;
	}
	return num;
}

快速方法位运算:
int fuc2(int x)
{	
	int ret=0;
	while(x!=0)
	{	
		ret=ret|(x&1);
		x=x>>1;
		if(x!=0)
		ret=ret<<1;
	}
	return ret;
}

位运算的递归写法:
int fuc3(int x,int ret)
{
	
	ret=ret|(x&1);
	if(x>>1!=0) 
	{	
		int num=fuc3(x>>1,ret<<1);
		return num;
	}
	return ret;

}



【C语言】逆转二进制数的几种方法

原文:http://blog.csdn.net/a781558066/article/details/42215969

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!