You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何LeetCode Single Number II中看似相同的条件结果不同?

LeetCode Single Number II 代码疑问

我在解决LeetCode的Single Number II问题时,编写了如下代码:

class Solution {
public:
    Solution ()
    {
        ios_base::sync_with_stdio(0);
        cin.tie(0);
        cout.tie(0);
    }
    int singleNumber(vector<int>& nums) {
        int ans = 0;
        for(int i = 0 ; i < 32 ; i++)
        {
            int count = 0 ;
            for(int j = 0 ; j < nums.size() ; j++)
            {
                if((nums[j]&(1<<i))==1) count++;
            }
            if(count%3!=0) ans = ans|(1<<i);
        }
        return ans;
    }
};

当输入nums = [2,2,3,2]时,这段代码输出的结果是1,但预期输出应为3。正确的代码如下:

class Solution {
public:
    Solution ()
    {
        ios_base::sync_with_stdio(0);
        cin.tie(0);
        cout.tie(0);
    }
    int singleNumber(vector<int>& nums) {
        int ans = 0;
        for(int i = 0 ; i < 32 ; i++)
        {
            int count = 0 ;
            for(int j = 0 ; j < nums.size() ; j++)
            {
                if((nums[j]&(1<<i))!=0) count++;
            }
            if(count%3!=0) ans = ans|(1<<i);
        }
        return ans;
    }
};

两段代码的唯一区别在于条件判断语句:我写的是if((nums[j]&(1<<i))==1),而正确代码用的是if((nums[j]&(1<<i))!=0)。我原本觉得这两种写法逻辑等价,请问我忽略了什么细节?


内容的提问来源于stack exchange,提问作者Om Surase

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 05:36:16