gpt4 book ai didi

c++ - 位运算与

转载 作者:太空狗 更新时间:2023-10-29 20:22:42 26 4
gpt4 key购买 nike

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

例如:给定 nums = [1, 2, 1, 3, 2, 5],返回 [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 中,&& 和 || 运算符添加的较晚,所以它的优先级非常低,因此不会破坏遗留程序。

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显示运算符优先级。 enter image description here
显示 != 的优先级高于 &

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

if ( differbit & (i!=0) )

而不是我假设你打算做的:

if ( (differbit & i) != 0 )

关于c++ - 位运算与,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36784470/

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