2

我想对多个操作数进行按位运算,以便当只有一个整数在该位置有 1 位时输出整数为 1,否则为 0。

我正在使用: (a ^ b ^ c ^ d ^ e ^ f ^ g ^ h ^ i) ^ (a & b & c & d & e & f & g & h & i)

a: 0000001000
b: 0000000010
c: 1010000000
d: 0000110000
e: 0001000000
f: 0000110000
g: 1000100000
h: 0000000100
i: 0100000000

我想得到:

   0111001110

但是,我得到:

   0111101110

知道为什么吗?或者我应该修改什么?

4

2 回答 2

5

实际上,您可以使用按位运算来计算。

int atLeastOne = 0将是一个掩码,指示在 1 个或多个输入中设置的位。

int moreThanOne = 0将是一个掩码,指示在 2 个或更多输入中设置的位。

可以通过以下方式将输入x“添加”到该状态:

// if a bit has been set already and it is set again now, it has been set more than once
moreThanOne |= atLeastOne & x;
// if a bit is set now, it is set at least once
atLeastOne |= x;

只需对所有内容执行此操作(一开始就进行简化):

atLeastOne = a;
moreThanOne |= atLeastOne & b;
atLeastOne |= b;
moreThanOne |= atLeastOne & c;
atLeastOne |= c;
moreThanOne |= atLeastOne & d;
atLeastOne |= d;
moreThanOne |= atLeastOne & e;
atLeastOne |= e;
moreThanOne |= atLeastOne & f;
atLeastOne |= f;
moreThanOne |= atLeastOne & g;
atLeastOne |= g;
moreThanOne |= atLeastOne & h;
atLeastOne |= h;
moreThanOne |= atLeastOne & i;
atLeastOne |= i;

如果至少设置了一次且不超过一次,则该设置了一次:

int exactlyOne = atLeastOne & ~moreThanOne;
于 2017-04-23T00:15:33.033 回答
0

这是另一种方法:

int a = 8;
int b = 2;
int c = 640;
int d = 48;
int e = 64;
int f = 48;
int g = 544;
int h = 4;
int i = 256;
int result = 0;
int [] arr = {a,b,c,d,e,f,g,h,i};

// go through all positions
for (int j = 0; j < 32; j++)
{
    int ones = 0;
    // go through each number for this position
    for (int k = 0; k < arr.length; k++)
    {
        int val = arr[k] & (1 << j);
        ones += (val > 0) ? 1 : 0;
    }
    result += (ones == 1) ? (1 << j) : 0;
}
System.out.println(result);
System.out.println(Integer.toBinaryString(result));

输出

462
111001110
于 2017-04-23T00:47:47.543 回答