1.与 &
2.或 |
3.取反 ~
4.异或 ^(两个数一样就是0,两个不一样是1)
5.右移 ps:11011 >>1 变成1101 >>2变成110
总的来说:右移就是这个被右移的数除以2的被移了几次的几次方 Ps:a>>k -> a/2^k
6.左移
往后补0就对了 ps:a<<k -> a*2^k
题目:
acwing89. a^b
90. 64位整数乘法
acwing89. a^b
实际上这是个快速幂用到位运算第一个性质(整数n的二进制数的第k位数=n>>k&1)
#include<iostream>
using namespace std;
int main()
{
int a,b,p;
cin>>a>>b>>p;
int res = 1 % p;//避免出现特殊情况
while(b)
{
if(b & 1) res = (long long)res * a % p;
b>>=1;
a = (long long)a * a % p;//数据范围太大需要long long 辅助
}
cout<<res<<endl;
return 0;
}
90. 64位整数乘法
//跟上一题类似,只不过这题可以利用加法代替乘法来做
#include<iostream>
using namespace std;
#define ll long long
int main()
{
ll a,b,p;
ll res = 0;
cin>>a>>b>>p;
while(b)
{
if(b&1)res = (res + a) % p;
a = a*2 % p;
b>>=1;
}
cout<<res<<endl;
return 0;
}
常见函数:
1.reverse(翻转)
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
vector<int>a({1,2,3,4,5});
reverse(a.begin(),a.end());
for(int x:a)cout<<x<<" ";
return 0;
}
输出:5 4 3 2 1
2.unique(去重)
必须保证相同元素挨在一起
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
int a[] = {1,2,2,3,3,4,4,5};
int m = unique(a, a + 8) - a;//求数的个数
cout << m << endl;
for(int i = 0;i < m;i++) cout<<a[i]<<" ";//求整个元素的序列
cout<<endl;
return 0;
}
3.sort
sort(a.begin(),a.end());//从小到大排序
等价于:
bool cmp(int a,int b)//看看a是否应该排在b前面
{
return a < b;
}
sort(a.begin(),a.end(),greater<int>{});//从大到小排序