Sum of two integers#
Practice Link#
LeetCode
Description#
- Calculate the sum of two integers a and b, but you are not allowed to use the operator
+ and -.
Example#
1Input: a = 1, b = 2
2Output: 3
Python Solution#
1# Add without using arithmetic operator
2def Add(x, y):
3
4 # Iterate till there is no carry
5 while (y != 0):
6
7 # carry now contains common
8 # set bits of x and y
9 carry = x & y
10
11 # Sum of bits of x and y where at
12 # least one of the bits is not set
13 x = x ^ y
14
15 # Carry is shifted by one so that
16 # adding it to x gives the required sum
17 y = carry << 1
18
19 return x
20
21
22print(Add(15, 32))