Moore's Voting and Bit Manipulation Approach


#1
#include<bits/stdc++.h>
int Solution::majorityElement(const vector<int> &A) {
    /* Moore's Voting
    int curMajor=A[0],cnt=1;
    for(int i=1;i<A.size();i++){
        if(A[i]==curMajor)
            cnt++;
        else
            cnt--;
        if(cnt==0){
            curMajor=A[i];
            cnt=1;
        }
            
    }
    return curMajor;
    */
    int n=A.size();
    vector<int> v(32,0);
    for(auto i:A){
        string s=bitset<32>(i).to_string();
        for(int j=0;j<32;j++){
            if(s[j]=='1')
                v[j]++;
        }
    }
    string ans="";
    for(auto i:v){
        i>n/2?ans+='1':ans+='0';
    }
    return stoi(ans,0,2);
    
}