这道题是不常使用的位运算题目,使用位运算的代码十分精简
#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;
}