BJUTACM 1089:Cw的嘲讽

本文介绍了一种使用位运算解决问题的方法,通过位运算实现对二进制数的高效操作。提供了两种实现方式,一种利用位运算简化代码,另一种采用常规算法进行对比。适合希望了解位运算及其应用的读者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接

这道题是不常使用的位运算题目,使用位运算的代码十分精简

#include <iostream>
#include <algorithm>
#include <stack>
#include <queue>
#include <vector>
#include <cstring>
#include <cmath>
#include <cstdlib>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;

int main(int argc, char** argv) {
	long long x;
	scanf("%lld",&x);
	int count = 0; 
	while(x&1)
	{
		long long temp;
//		temp = x>>1;
//		x = temp;
		x>>=1; //右移 
		count ++;
	}
	for(int i=0;i<count;i++)
	{
		x<<=1;
	}
	printf("%lld",x);

	//system("pause");
	return 0;
}

注意位运算左移时自动补0,右移时自动删除,使用十进制数可以直接进行位运算

运算符&可以比对两个数,如果二进制位都是1,就返回1,其余情况均返回0

<<= 的操作类似于之前的+= *= 因为都是运算符


附上以前不用位运算的代码,佩服当时的自己。。。

#include <stdio.h>
long long er(int n); 
int main(void)
{
	long long x; 
	scanf("%lld",&x);
	long long  o = x;
	char s[100000];
	long i=0;
	while(x != 0)
	{
		s[i] = x % 2  + '0';
		x = (x - x%2)/2;
		i ++;
	 } 
	 long long j; 
	int cunchu[1000];
	long t = 0;	
	if(i!=0)
	{ 
	 for(j=i-1;j>=0;j--)//反向存储 
	 {
	 	cunchu[t] = s[j];
	 	t++;
	 }
	}
	int count = 0; 
	while(cunchu[t-1]=='1')
	{
		count ++;
		t--;
	 }
	long long sum = 0;
	 for(i=0;i<count;i++)
	 {
		sum += er(i);
	  } 
	  printf("%lld",o-sum);
	  return 0;

 } 
 long long er(int n)
 {
 	long long total=1;
 	int i;
 	for(i=0;i<n;i++)
 	{
 		total *= 2;
	 }
	 return total;
 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值