其實你可以計算,按位運算。
int atLeastOne = 0
將是一個掩碼,指示在一個或多個輸入中設置的位。
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;
你會需要一個循環做到這一點,因爲每個比較而言依賴於結果以前的比較。 – Tibrogargan