Input = [-2,-2,1,1,4,1,4,4,-4,-2]
How to handle negative numbers for unique number 3
hey @ksalokya In the approach taught in the video, we are doing shift operations on the given numbers. Remember that The left shift and right shift operators should not be used for negative numbers.Left shifting and right shifting negative numbers always introduces a leftmost set bit(signed bit). Due this problem arises as this can never turn to 0 by right shifting or left shifting. The result of is undefined behaviour if any of the operands is a negative number. Due to this reason the code is failing for negative numbers.
One approach to solve the problem by avoiding the shifting operations on the original number:
(Please dry run with any sample case to understand the code. The approach is somewhat similar to the previous one)
//Here we are reserving the 32 bits space for the final resulting number and setting the bits accordingly
//Note that here we are not performing shifting operation on the numbers stored in the vector
int uniquenumber(vector< int >& nums) {
int res = 0;
int len=nums.size();
for(int i=0; i<32; i++)
{
int mask = (1 << i);
int count = 0;
for(int j=0; j<len; j++)
if(mask&nums[j]) count++;
if(count%3)
res |= (1<<i);
}
return res;
}
thank you. you can close this thread.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.