C Program to find the element present only one time while other elements are present k times - Bit Manipulation

 


// Program by Akash Tripathi (@proakash256) 
 
// In an Integer Array , all the Numbers
// are present k times except one.
// Find that Integer in O(n) time
// complexity and O(1) Space Complexity.

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int n , result = 0 , k;
    printf("Enter the number of elements
you want to enter : ");
    scanf("%d", &n);
    int ar[n];
    printf("\nEnter the Elements :\n");
    for (int i = 0i < ni = i + 1)
        scanf("%d", &ar[i]);
    printf("\nEnter the value of k : ");
    scanf("%d", &k);
    int *count = (int*)calloc(32 , sizeof(int));
    for(int i = 0i < 32i = i + 1)
    {
        for(int j = 0j < nj = j + 1)
        {
            if((ar[j] & (1 << i)) != 0)
            {
                count[i] = count[i] + 1;
            }
        }
    }
    for (int i = 0i < 32i = i + 1)
    {
        result = result +
((count[i] % k) * (1 << i));
    }
    printf("\nThe Element is %d." , result);
    return 0;
}

Comments