Single Number II @LeetCode

PROBLEM :

Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        if(nums.size()==1)
            return nums[0] ;
           
        int result=0 ;
        for(int i=0;i<32;i++){
            int count=0 ;
            int temp ;
           
            temp=(1<<i) ;
            for(int j=0;j<nums.size();j++)
                if(nums[j]&temp)
                    count++ ;
                   
            if(count%3)
                result=result|temp ;
        }
        return result ;
    }
};

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )