Thursday 5 January 2017

Find the element that appears once (Bit Algorithms)

Example:-
input:- 12, 1, 12, 3, 12, 1, 1, 2, 3, 3
frequency:- 3
ans:- 2
Because other all number except 2 appears more than onces and same number of time. In this program k is other number frequency which are same for all the number except one number. 

Complexity:-
Expected time complexity is O(n) and O(1) extra space.

Program:-

#include <bits/stdc++.h>
using namespace std;

class bits{
    int max_size,n,k,result;
    public:
    int *arr;
    bits(int n1,int k1){
        max_size=32;
        k = k1;
        n=n1;
        result=0;
        arr = (int *)malloc(sizeof(int)*n1);
    }
    void input();
    void bitsnumber();
};

void bits::input(){
    for(int i=0;i<n;i++) cin>>arr[i];
}

void bits::bitsnumber(){
    int num,sum=0;
    for(int i=0;i<max_size ;i++){
        num=1<<i;
        sum=0;
        for(int j=0;j<n;j++)
            if(num & arr[j]) sum++;
            if(sum%k) result = result | num;
    }
    cout<<"The number which appears exactly one is: ";
    cout<<result<<endl;
}
int main()
{
    int n,k;
    cout<<"Enter the number of element 'n' and other number which frequency is exactly 'k' times\n";
    cin>>n>>k;
    cout<<"Enter n number\n";
    bits b(n,k);
    b.input();
    b.bitsnumber();
    return 0;
}

No comments:

Post a Comment