fun uniqueNum(nums: List<Int>): Int {
return nums.reduce { a, b -> a xor b }
}
#Challenge
Source | Language | Runtime |
---|---|---|
leetcode | kotlin |
given a non empty array of integers with the guarantee that every number occurs twice except one. Find the number that occurs only once.
#Solution
This implementation takes advantage of the fact that nums
cancels itself out in num
(
#Test Cases
uniqueNum(listOf(1,2,3,2,1)) // 3
uniqueNum(listOf(1)) // 1
uniqueNum(listOf(2,2,1)) // 1
uniqueNum(listOf(4,1,2,1,2)) // 4