Why are same conditions getting different results?

48 Views Asked by At

I am solving question. and this is the code written by me

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;
    }
};

for input of nums = [2,2,3,2] my output is 1 but expected output is 3.

where as the correct code is as follows

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;
    }
};

both the code differ in if((nums[j]&(1<<i))!=0) count++; condition only which seem same to me. what am i missing?

1

There are 1 best solutions below

1
MikeCAT On

Your condition (nums[j]&(1<<i))==1 is true only when the value of (nums[j]&(1<<i)) is 1.

On the other hand, the condition (nums[j]&(1<<i))!=0 is true whenever the value of (nums[j]&(1<<i)) is not 0.

(nums[j]&(1<<i)) can be values other than 0 nor 1. For example, the value is 2 when nums[j]=3 and i=1.

If you want to use ==1, you can use ((nums[j]>>i)&1)==1.