-
Notifications
You must be signed in to change notification settings - Fork 4.7k
Expand file tree
/
Copy pathadd_bitwise_operator.py
More file actions
39 lines (30 loc) · 966 Bytes
/
Copy pathadd_bitwise_operator.py
File metadata and controls
39 lines (30 loc) · 966 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
"""
Add Bitwise Operator
Add two positive integers without using the '+' operator, using only
bitwise operations (AND, XOR, shift).
Reference: https://en.wikipedia.org/wiki/Adder_(electronics)
Complexity:
Time: O(log n) where n is the larger of the two inputs
Space: O(1)
"""
from __future__ import annotations
def add_bitwise_operator(first: int, second: int) -> int:
"""Add two non-negative integers using only bitwise operations.
Args:
first: First non-negative integer operand.
second: Second non-negative integer operand.
Returns:
The sum of first and second.
Examples:
>>> add_bitwise_operator(2, 3)
5
>>> add_bitwise_operator(0, 0)
0
"""
if first < 0 or second < 0:
raise ValueError("The provided values must be non-negative!")
while second:
carry = first & second
first = first ^ second
second = carry << 1
return first