位运算

程序中的所有数在计算机内存中都是以二进制的形式储存的。
位运算就是直接对整数在内存中的二进制位进行操作。

(一)&(按位与)
同为1则为1,否则为0。比如6&3,6的二进制表示为0110,3的二进制表示为0011,按照&的运算规则,0110&0011=0010,所以6&3=2。
应用:
①可以用来消去二进制中最后面的一个1。比如6的二进制表示0110,最后面的1为第三个数,要将此1消去,只要6&(6-1)即可,5的二进制表示为0101,0110&0101=0100,这样就消去了最后面的1。
②可以用来计算一个二进制数中有多少个1。只要不断进行n&(n-1)的操作。

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<iostream>
using namespace std;
int main()
{
    int n,ans=0;
    scanf("%d",&n);
    while(n)
    {
        n&=(n-1);
        ans++;
    }
    printf("%d\n",ans);
    return 0;
}

(二)|(按位或)
只要有一个为1,结果就是1,否则为0。比如6&3,6的二进制表示为0110,3的二进制表示为0011,按照|的运算规则,0110|0011=0111,所以6|3=7。
应用:
(三)^(按位异或)
相同为0,不同为1。比如6^3,6的二进制表示为0110,3的二进制表示为0011,按照 ^的运算规则,0110 ^0011=0101,所以6 ^3=5。
应用:
①0 ^n=n,n ^n=0。可以用来寻找一组两两重复的数中单独的数。
比如下面这题:
In the new year party, everybody will get a “special present”.Now it’s your turn to get your special present, a lot of presents now putting on the desk, and only one of them will be yours.Each present has a card number on it, and your present’s card number will be the one that different from all the others, and you can assume that only one number appear odd times.For example, there are 5 present, and their card numbers are 1, 2, 3, 2, 1. so your present will be the one with the card number of 3, because 3 is the number that different from all the others.

    Input
    The input file will consist of several cases. 

Each case will be presented by an integer n (1<=n<1000000, and n is odd) at first. Following that, n positive integers will be given in a line, all integers will smaller than 2^31. These numbers indicate the card numbers of the presents.n = 0 ends the input.

    Output
    For each case, output an integer in a line, which is the card number of your present.

    Sample Input
    5

1 1 3 2 2
3
1 2 1
0

    Sample Output
    3

2
题意为:有一大堆礼物,每个礼物上有一个编号,里面只有一个编号是一个,其他都是两个,这个就是你的礼物,找到它。这题如果用 ^非常简单。

#include<stdio.h>
int main()
{
    int n,x,a,i;
    scanf("%d",&n);
    if(n==0)
    return 0;
    else
    {
    x=0;
    for(i=0;i<n;i++)
    {
        scanf("%d",&a);
        x=x^a;
    }
    printf("%d\n",x);
    }
    return 0;
}

(四)~(按位取反)
在二进制中,1变为0,0变为1。
(五)<<(按位左移)
把一个数的二进制左移,左移几位就相当于乘以2的几次幂,因为是底层运算,所以速度较快。
(六)>>(按位右移)
把一个数的二进制右移,右移几位就相当于除以2的几次幂,因为是底层运算,所以速度较快。

熟练运用位运算,能很大程度上优化程序!!

参考文献:百度百科

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值