Find the number which occurs once

Given an array of integers where every integer occurs three times except for one integer, which only occurs once, find and return the non-duplicated integer.

For example, given [6, 1, 3, 3, 3, 6, 6], return 1. Given [13, 19, 13, 13], return 19.

Example:

Input:  arr[]={6,1,3,3,3,6,6}
Output: 1

Approach

C++

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

int singleNumber(vector<int>& nums
{
    int first=0,second=0,third;
    int n=nums.size();

    //iterate till the end of array
      for(int i=0;i<n;i++)
       {
           //update second
           second=second|(first&nums[i]);

           //update first
           first=first^nums[i];

           //update third
           third=~(first&second);
           first=first&third;
           second=second&third;
       }
        return first;
        
}
int main()
{
    vector<intnums = {6133366};

    cout << singleNumber(nums);

    return 0;
}


No comments:

Post a Comment