实际上,您可以使用按位运算来计算。
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;