函数计算一个数组中有多少个值与给定的键互补
Function to count how many values in an array complement with a given key
我尝试了一种算法,该算法将计算矩阵中有多少元素用给定键的最后S个位数来补充其最后个S位。
假设s等于3,要验证的数字是12,密钥是3。在二进制表示中,12=(00001100)和3=(00000011)。如果我们将xor应用于这两个值,我们得到15(00001111)。但我们只考虑最后的S(3)位,因为它们都等于1,所以数字是互补的。如果我们有相同的数字12,但密钥是5(00000101),那么xor的结果将返回9(00001001),但最后的S(3)位并不都是1,因此它不是互补的。
我试着在c++中实现这个算法,尽管我一遍又一遍地研究,但我似乎找不到其中的逻辑错误。我问你是因为这个代码用于我处理的一个问题,而自动评估它的网站并没有授予它这个子问题所能获得的所有分数。
int complement()
{
//map is a globally declared matrix
//k is the key, also global
//S is the number of bits we take into account, also global
int i, j, nr=0, mask, aux;
mask = (1<<S)-1;
for(i=1; i<=n; i++)
for(j=1; j<=m; j++)
{
aux = map[i][j]^k;
if( aux & mask == mask)
{
map[i][j]=0; //overwritten as 0 meaning it is good
nr++;
}
else map[i][j]=-1; //overwritten as -1
}
return nr; //how many numbers could be complemented
}
For the matrix:
15 1278 3 1278 1278 1
16 17 18 19 254 20
21 25 26 254 254 254
27 28 29 3 2 254
2 254 4 254 254 254
The program returns:
-1 0 -1 0 0 -1
0 -1 0 -1 0 0
-1 -1 0 0 0 0
-1 0 -1 -1 0 0
0 0 0 0 0 0
and nr = 20.
限制:
- S<=8
- 所有值和键<=9999
C/C++运算符的逐位操作优先级是"错误的"。
在C/C++中
aux & mask == mask
被解析为
aux & (mask == mask)
你需要写
(aux & mask) == mask
因为否则CCD_ 1每次都将以1结束并且与掩模大小无关。
相关文章:
- 计算出有多少客户端可以连接到我正在使用的一些tcp服务器代码
- 如何计算整数链中使用了多少次数字?
- 我正在尝试计算文本文件中有多少销售人员 c++
- 计算有多少人执行我的C++应用程序
- 使用额外的变量使计算更容易理解 - (多少)我减慢了代码的速度?
- 如何计算图表中有多少种有效着色?
- 如何使程序谁将计算金字塔有多少个阶段
- 动态规划:计算集合中存在多少个升序子集
- 如何计算排队多少个字?更智能的方式
- 该递归代码用于计算指数的运行时间是多少
- 计算 QTextEdit 中有多少行
- 如何计算有多少个带有坐标 (x;y) 的点在圆圈内/圈上/圈外
- 如何计算在Sentinel Loop C 中输入多少次输入
- 通过给定输出,程序计算中使用了多少个项
- 在计算使用了多少个数组索引的同时,如何填充一个来自用户输入的字符的数组?(使用cin.get)
- 是否可以计算出有多少 CPU 和 RAM 使用代码块
- 计算向量中值的最小差值的此函数的算法复杂度是多少
- 计算出一个程序(规划中)需要多少内存
- 如何计算循环执行了多少次?C++
- 如何将特定数量的字符转换为大写或小写,并计算单词有多少个大写和小写字母