Have some doubts in the operation (n<<32) [Bitwise Manipulation]

Revision en2, by abhinav700, 2022-09-20 07:17:20

I was doing a question on leetcode and the part of it's solution required to find the rightmost set bit of an integer(it can also be negative).It is given that integer is a 32 bit number in constraints.

While finding out the position of right most bit using below function

int findPos(int allXor){
        int flag=1;
        int i;
        for( i=0;i<=32;i++)
            if((1<<i) & allXor )
                break;
        return i;
    }

i am unable to understand that how 1<<32 is going to work. It is because we are given a 32 bit number and 1<<32 would represent the integer which has it's 33rd bit set right? when i use i<=31 in this question i get the wrong answer.

Can someone pls explain what is happening here?

QUESTION LINK: https://leetcode.com/problems/single-number-iii/

FULL CODE:

class Solution {
public:
    int findPos(int allXor){
        int flag=1;
        int i;
        for( i=0;i<=32;i++)
            if((1<<i) & allXor )
                break;
        return i;
    }
    
    vector<int> singleNumber(vector<int>& nums) {
        if(nums.size()==2)
            return nums;
        vector<int> ans;
        int allXor=0;
        for(auto it: nums)
            allXor^=it;
        int bitPos=findPos(allXor);
        // cout<<allXor<<" "<<bitPos<<endl;
        vector<int> part1,part2;
        
        for(auto it: nums){
            if((1<<bitPos)&it)
                part1.push_back(it);
            else
                part2.push_back(it);
        }
        
        int element1=0,element2=0;
        for(auto it : part1)
        {
              element1^=it;
              cout<<it<<" ";
        }
        cout<<endl;
        for(auto it : part2)
        {
               element2^=it;
                cout<<it<<" ";
        }
        return {element1,element2};
    }
};
Tags c++, bitmask, doubt, concept learning

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en2 English abhinav700 2022-09-20 07:17:20 61 Tiny change: 'DE:\n```\nclass So' -> 'DE:\n```\n\nclass So' (published)
en1 English abhinav700 2022-09-20 07:12:37 1967 Initial revision (saved to drafts)