位运算与

bit operation AND

这是一道leetcode题。 给定一个数字数组 nums,其中正好有两个元素只出现一次,而所有其他元素正好出现两次。找出只出现一次的两个元素。

例如: 给定 nums = [1, 2, 1, 3, 2, 5], return [3, 5]。 我的代码是:

class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
int axorb=0;
    for(auto i:nums) axorb=axorb^i;
    int differbit=(axorb&(axorb-1))^axorb;
    int group3=0, group5=0;
    for(auto i:nums)

if(differbit&i!=0) group5=group5^i;

        else group3=group3^i;
        return vector<int>{group3,group5};

}
};

提交结果为错误答案。

Input:[0,0,1,2]
Output:[3,0]
Expected:[1,2]

但如果我只是将突出显示的部分更改为

if(differbit&i) group5=group5^i;

已接受。 我花了很多时间思考但仍然没有想法。也许发生了某种类型转换?谢谢

这与运算符优先级有关。
因为在早期的 C 中,&& and || 运算符添加的较晚,所以它的优先级非常低,因此不会破坏遗留程序。

这个 Stack overflow Question 对于原因有一个很好的答案:

From this forum: http://bytes.com/topic/c/answers/167377-operator-precedence

The && and || operators were added later for their "short-circuiting" behavior. Dennis Ritchie admits in retrospect that the precedence of the bitwise operators should have been changed when the logical operators were added. But with several hundred kilobytes of C source code in existence at that point and an installed base of three computers, Dennis thought it would be too big of a change in the C language...


这里 A Table 显示运算符优先级。
显示 != 的优先级高于 &

如您所见,bitwise & 低于 table 上的 !=,因此您的代码正在执行以下操作:

if ( differbit & (i!=0) )

而不是我认为你打算做的事情:

if ( (differbit & i) != 0 )