c – 按位比较
作者:互联网
#include <iostream>
using namespace std;
int main() {
int n, a = 0xfffffff;
cin >> n;
while (n--) {
string s;
cin >> s;
int c = 0;
for (char ch : s)
c |= 1 << (ch - 'a');
a &= c;
}
cout << __builtin_popcount(a) << endl;
return 0;
}
该代码用于查找字符是否存在于所有输入的字符串中至少一次.
有人可以解释这段代码中发生的事情.
我试图在C中学习一些明智的操作,我无法理解这里发生的事情.
解决方法:
代码不是确定所有字符串中是否存在特定字符.
它是查找所有字符串中存在的字符数.
这是代码的细分.
int n, a = 0xfffffff;
cin >> n;
n是来自用户的输入参数,用于确定字符串的数量.假设n是3
while (n--) {
string s;
cin >> s;
int c = 0;
for (char ch : s)
c |= 1 << (ch - 'a');
a &= c;
}
这是代码的主要部分..
你得到n个字符串,对于每个字符串,你可以在一个位数组中存储它由它组成的字符
例如,让我们说第一个字符串是“堆栈”.你循环通过这里的人物
for (char ch : s)
c |= 1 << (ch - 'a');
对于每个字符串,c被初始化为0.
在这个例子“堆栈”中,让我们看看c会发生什么
c = c | 1 << (‘s’-‘a’) => c = c | 1 << 18 (18th bit of c is set to 1)
c = c | 1 << (‘t’-‘a’) => c = c | 1 << 19 (19th bit of c is set to 1)
c = c | 1 << (‘a’-‘a’) => c = c | 1 << 0 (0th bit of c is set to 1)
c = c | 1 << (‘c’-‘a’) => c = c | 1 << 2 (2nd bit of c is set to 1)
c = c | 1 << (‘k’-‘a’) => c = c | 1 << 10 (10th bit of c is set to 1)
note that 1 << n means that 1 is left shifted by n digits. so 1 << 3 is = 0001 << 3 = binary 1000 = 2^3 = 8 (In case you did not understand shifting)
现在c是一个整数,其0,2,10,18,19位设置为1. a在循环之前初始化为全1.
a &= c; this gets rid of all 1’s except 0,2,10,18 and 19.
我们继续为所有字符串.最后,a将在所有字符串中占用的位置设置1位.
例如,如果字符串2是“aaaaa”
computing c reveals that c has only its 0th bit set.
a &= c; this gets rid of all 1’s except 0 (ie., it sets 2,10,18 and 19th bits to 0, since they don’t occur in “aaaaa”)
而字符串3是“zzzzza”,最后,只设置第0位
因此,所有这些字符串中出现的字符数为1
标签:c,bitwise-operators,bit-manipulation 来源: https://codeday.me/bug/20190722/1502767.html