Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- Logic:
- sum of 010 and 101 is 111 and xor of 010 and 101 is also same.
- but sum and xor of 001 and 001 is not same because lsb bits sum ie. 1+1 =0 and 1 carry.
- so we will do xor of a and b in a so a will be having the sum of those bits where there
- is no carry.we can find the carry bits using & opearator.ofcourse we shift carry while
- sum 1 bit so do the same and add carry again.
- Here we are using unsigned for keeping that is must otherwise shifting will go overflow.
- mask is used here because negative numbers can go more than 32 bits
- '''
- class Solution:
- def getSum(self, a: int, b: int) -> int:
- MASK = 0xFFFFFFFF
- MAX_INT = 0x7FFFFFFF #maximum possible number in 32 bit ie. 2^32-1 or 01111111 11111111 11111111 11111111
- while b != 0: #addition happens normally,sum the bits and add carry in one left like we do normally
- carry = (a & b) & MASK
- a = (a ^ b) & MASK
- b = (carry << 1) & MASK
- # convert back to signed integer
- return a if a <= MAX_INT else ~(a ^ MASK) #when a=negative number then it will be larger than 32 bit but python thinks it is a positive number,so masking ro bringing to the 32 bit and then fliping to make it negative number
Advertisement
Add Comment
Please, Sign In to add comment