Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 如何使用位运算符求解_C - Fatal编程技术网

C 如何使用位运算符求解

C 如何使用位运算符求解,c,C,我想知道哪个抽屉是满的。但是输出必须是一个对应于二进制表示的数字。例如,如果只有第二个抽屉已满(从左到右),则输出为4: 8 4 2 1 0 1 0 0(第二抽屉已满) 所以我用了这个方法 int DrawersFull[4] = {0,0,0,0}; //Initially all are empty for(i=0;i<4;i++) { if(IsDrawerFull) // the api was provided by the interviewer Dra

我想知道哪个抽屉是满的。但是输出必须是一个对应于二进制表示的数字。例如,如果只有第二个抽屉已满(从左到右),则输出为4:

8 4 2 1

0 1 0 0(第二抽屉已满)

所以我用了这个方法

int DrawersFull[4] = {0,0,0,0}; //Initially all are empty

for(i=0;i<4;i++)
{

    if(IsDrawerFull) // the api was provided by the interviewer
      DrawerFull[i]=1;
}
int-DrawersFull[4]={0,0,0}//最初所有的都是空的

对于(i=0;i这与将二进制数转换为十进制数相同。请尝试以下方法:

int res = 0;
for (i = 4; i >= 1; i--) {
    res = res * 2 + DrawerFull[i]; // Assuming DrawerFull will contain only 1 or 0.
}
char fullDrawers=0;
对于(字符i=0;i<4;++i)
{
if(IsDrawerFull)
满抽屉&=1;

fullDrawers您是在谈论数组还是位运算符(您似乎不使用后者中的任何一个)?您的循环也应该是
for(i=0;i您是否试图返回一个
int
来描述哪些抽屉已满?问题不清楚。您的输入数字是:(8,4,2,1)或者您的输出?输出的形式是什么-数组或未指定(可以是标量)?这是一个base 2算术问题,但您的问题描述不清楚。我相信'8 4 2 1'表示二进制位置的值。IsDrawerFull函数是一个api,它将根据抽屉中已满的抽屉将数组设置为正确的值。他询问如何使用与dir相对应的位运算来计算值特别是那个数组中的值。由于这个问题被搁置,我无法回答它…以下是我的解决方案:
int res=0;for(int I=0;I<4;I++){if(IsDrawerFull(I))res |=8>>I;}
char fullDrawers = 0;
for( char i = 0; i < 4; ++i )
{
    if( IsDrawerFull )
        fullDrawers &= 1;
    fullDrawers <<= 1;
}