mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-04-24 06:33:37 +00:00
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>
This commit is contained in:
parent
4ed61418a8
commit
cc621f1fdd
37
bit_manipulation/find_unique_number.py
Normal file
37
bit_manipulation/find_unique_number.py
Normal file
@ -0,0 +1,37 @@
|
|||||||
|
def find_unique_number(arr: list[int]) -> int:
|
||||||
|
"""
|
||||||
|
Given a list of integers where every element appears twice except for one,
|
||||||
|
this function returns the element that appears only once using bitwise XOR.
|
||||||
|
|
||||||
|
>>> find_unique_number([1, 1, 2, 2, 3])
|
||||||
|
3
|
||||||
|
>>> find_unique_number([4, 5, 4, 6, 6])
|
||||||
|
5
|
||||||
|
>>> find_unique_number([7])
|
||||||
|
7
|
||||||
|
>>> find_unique_number([10, 20, 10])
|
||||||
|
20
|
||||||
|
>>> find_unique_number([])
|
||||||
|
Traceback (most recent call last):
|
||||||
|
...
|
||||||
|
ValueError: input list must not be empty
|
||||||
|
>>> find_unique_number([1, 'a', 1])
|
||||||
|
Traceback (most recent call last):
|
||||||
|
...
|
||||||
|
TypeError: all elements must be integers
|
||||||
|
"""
|
||||||
|
if not arr:
|
||||||
|
raise ValueError("input list must not be empty")
|
||||||
|
if not all(isinstance(x, int) for x in arr):
|
||||||
|
raise TypeError("all elements must be integers")
|
||||||
|
|
||||||
|
result = 0
|
||||||
|
for num in arr:
|
||||||
|
result ^= num
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
import doctest
|
||||||
|
|
||||||
|
doctest.testmod()
|
Loading…
x
Reference in New Issue
Block a user