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?
Your condition
(nums[j]&(1<<i))==1is true only when the value of(nums[j]&(1<<i))is1.On the other hand, the condition
(nums[j]&(1<<i))!=0is true whenever the value of(nums[j]&(1<<i))is not0.(nums[j]&(1<<i))can be values other than0nor1. For example, the value is2whennums[j]=3andi=1.If you want to use
==1, you can use((nums[j]>>i)&1)==1.