Skip to content

Commit cc621f1

Browse files
Add find_unique_number algorithm to bit manipulation (#12654)
* Add find_unique_number algorithm to bit manipulation * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 4ed6141 commit cc621f1

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

Diff for: bit_manipulation/find_unique_number.py

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
def find_unique_number(arr: list[int]) -> int:
2+
"""
3+
Given a list of integers where every element appears twice except for one,
4+
this function returns the element that appears only once using bitwise XOR.
5+
6+
>>> find_unique_number([1, 1, 2, 2, 3])
7+
3
8+
>>> find_unique_number([4, 5, 4, 6, 6])
9+
5
10+
>>> find_unique_number([7])
11+
7
12+
>>> find_unique_number([10, 20, 10])
13+
20
14+
>>> find_unique_number([])
15+
Traceback (most recent call last):
16+
...
17+
ValueError: input list must not be empty
18+
>>> find_unique_number([1, 'a', 1])
19+
Traceback (most recent call last):
20+
...
21+
TypeError: all elements must be integers
22+
"""
23+
if not arr:
24+
raise ValueError("input list must not be empty")
25+
if not all(isinstance(x, int) for x in arr):
26+
raise TypeError("all elements must be integers")
27+
28+
result = 0
29+
for num in arr:
30+
result ^= num
31+
return result
32+
33+
34+
if __name__ == "__main__":
35+
import doctest
36+
37+
doctest.testmod()

0 commit comments

Comments
 (0)