Lonely Integer

Sort by

recency

|

913 Discussions

|

  • + 0 comments

    //C#

    public static int lonelyinteger(List a) {

       int unique = 0;
       foreach (int n in a )
       {
         unique ^= n;
       }
       return unique;
    
    
    }
    
  • + 0 comments

    Javascript users... a.reduce((acc, num) => acc ^ num, 0);

    Use the XOR operator.

  • + 0 comments

    This is the solution in scala def lonelyinteger(a: Array[Int]): Int = { a.foldLeft(0)(_ ^ _) }

  • + 0 comments

    C++ deserves more love :(

    int lonelyinteger(vector<int> a) {
    
        // Use a set to track numbers we've encountered as we iterate through
        set<int> b;
        
        for (int i : a) {
            // If we lookup i and it doesn't return the end iterator
            if( b.find( i ) != b.end() )
            {
                b.erase( i ); // Remove the already encountered integer
            } else {
                b.emplace( i ); // Track encountered integer
            }
        }
        
        // Convert set to vector
        vector<int> b_vect( b.begin(), b.end() );
        
        // There should only be one element left...
        return b_vect.at(0);
    }
    
  • + 0 comments

    Wrote this solution by Swift, not perfect about alghoritms anyone can improve this for any suggest?

    func lonelyInteger(arr : [Int]) -> Int{
        
        var checkinNum = -1
        var count = 0
        var res = 0
        
        var sorted = arr.sorted(by: <)
        var uniqArr = Array(Set(sorted))
        
        uniqArr.forEach { num in
            checkinNum = num
            count = 0
            sorted.filter { filterNum in
                if checkinNum == filterNum {
                    count += 1
                    return true
                }
                else{
                    return false
                }
            }
            if count == 2{
                checkinNum = num
            }
            else{
                res = num
            }
        }
        return res
    }