From 9d29d1c547b75fca7154d385d5f7fad195dad87c Mon Sep 17 00:00:00 2001 From: parth-6945 <140963864+parth-6945@users.noreply.github.com> Date: Sat, 5 Apr 2025 14:04:58 +0530 Subject: [PATCH 1/2] Add find_unique_number algorithm to bit manipulation --- bit_manipulation/find_unique_number.py | 36 ++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 bit_manipulation/find_unique_number.py diff --git a/bit_manipulation/find_unique_number.py b/bit_manipulation/find_unique_number.py new file mode 100644 index 000000000000..4273bd2156e1 --- /dev/null +++ b/bit_manipulation/find_unique_number.py @@ -0,0 +1,36 @@ +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() From ec25e7d2203f736d3cdf2e5013a05d2936ebd292 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Sat, 5 Apr 2025 08:48:20 +0000 Subject: [PATCH 2/2] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- bit_manipulation/find_unique_number.py | 1 + 1 file changed, 1 insertion(+) diff --git a/bit_manipulation/find_unique_number.py b/bit_manipulation/find_unique_number.py index 4273bd2156e1..77970b4865d1 100644 --- a/bit_manipulation/find_unique_number.py +++ b/bit_manipulation/find_unique_number.py @@ -33,4 +33,5 @@ def find_unique_number(arr: list[int]) -> int: if __name__ == "__main__": import doctest + doctest.testmod()