# Find the element that appears once in an array where every other element appears twice in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

Suppose we have an array A. In this array there are different numbers that occurs twice. But there is only one number that occurs once. We have to find that element from that array.

Suppose A = [1, 1, 5, 3, 2, 5, 2], then the output will be 3. As there are each number twice, we can perform XOR to cancel out that element. because we know y XOR y = 0

To solve this, we will follow these steps.

• Take one variable res = 0

• for each element e in array A, preform res := res XOR e

• return res

## Example

Let us see the following implementation to get better understanding −

Live Demo

class Solution(object):
def singleNumber(self, nums):
ans = nums
for i in range(1,len(nums)):
ans ^=nums[i]
return ans
ob1 = Solution()
print(ob1.singleNumber([1,1,5,3,2,5,2]))

## Input

[1,1,5,3,2,5,2]

## Output

3