gpt4 book ai didi

java - Java 中多个操作数的按位异或

转载 作者:行者123 更新时间:2023-11-30 06:06:41 26 4
gpt4 key购买 nike

我想对多个操作数进行按位运算,以便当只有一个整数在该位置有 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

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

最佳答案

实际上,您可以通过按位运算来计算。

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;

关于java - Java 中多个操作数的按位异或,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43565897/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com