经典算法之位运算

1 位运算介绍

#include <iostream>
#include <string>
using namespace std;

int main()
{
	int a=12;//a= 00000000 00000000 00000000 00001100
	int b=6; //b= 00000000 00000000 00000000 00000110
	
	//按位与运算  输出4 
	cout<<(a&b)<<endl;

	//按位或运算 输出14
	cout<<(a|b)<<endl;

	//取反 输出-13		a= 00000000 00000000 00000000 00001100   ~a=11111111 11111111 11111111 11110011
	//补码  其值为  -00000000 00000000 0000000 00001101=-13
	cout<<(~a)<<endl;

	//右移 a= 00000000 00000000 00000000 00000110
	cout<<(a>>1)<<endl;

	float c=1.0;
	//cout<<(a&c)<<endl; 浮点数不能和整数进行位运算
	//cout<<(c>>1)<<endl;浮点数同样不能进行移位

	//字符支持移位运算  str=01100001 tar=0110010
	char str='a';
	char tar='b';
	cout<<(str>>1)<<endl;

	//字符支持位运算
	cout<<(str&tar)<<endl;

	return 0;
}

输出结果:



2 位算法




算法四的代码:

#include <iostream>
#include <string>
using namespace std;

//判断一个数转换为二进制后的1的位数
int num(int value)
{
	int temp=value;
	int k;
	int i=0;
	while(temp>0)
	{
		k=temp;
		temp=temp>>1;
		if(k-2*temp!=0)
		{
			i++;
		}
	}
	return i;
}
int main()
{
	cout<<num(10)<<endl;

	return 0;
}


  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值