How to find the number occurring an odd number of times in a sequence with Scala

1 Answer

0 votes
object OddOccurrence {
 
  def oddOccurrence(nums: Seq[Int]): Int = {
    // XOR all elements
    val xorValue = nums.foldLeft(0)(_ ^ _)
 
    // Verify that this value actually appears
    nums.find(_ == xorValue).getOrElse(-1)
  }
 
  def main(args: Array[String]): Unit = {
    val sq = Seq(2, 3, 7, 2, 8, 8, 8, 8, 3, 0, 0, 7, 7)
     
    println(oddOccurrence(sq))
  }
}
 
  
  
  
/*
run:
  
7
  
*/

 



answered Jan 30 by avibootz
edited Jan 30 by avibootz

Related questions

...