imashutosh51

Sum of Two Integers

Oct 16th, 2022 (edited)
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.23 KB | None | 0 0
  1. '''
  2. Logic:
  3. sum of 010 and 101 is 111 and xor of 010 and 101 is also same.
  4. but sum and xor of 001 and 001 is not same because lsb bits sum ie. 1+1 =0 and 1 carry.
  5. so we will do xor of a and b in a so a will be having the sum of those bits where there
  6. is no carry.we can find the carry bits using & opearator.ofcourse we shift carry while
  7. sum 1 bit so do the same and add carry again.
  8.  
  9. Here we are using unsigned for keeping that is must otherwise shifting will go overflow.
  10.  
  11. mask is used here because negative numbers can go more than 32 bits
  12. '''
  13.  
  14. class Solution:
  15.     def getSum(self, a: int, b: int) -> int:
  16.         MASK = 0xFFFFFFFF
  17.         MAX_INT = 0x7FFFFFFF #maximum possible number in 32 bit ie. 2^32-1 or 01111111 11111111 11111111 11111111
  18.  
  19.         while b != 0: #addition happens normally,sum the bits and add carry in one left like we do normally
  20.             carry = (a & b) & MASK
  21.             a = (a ^ b) & MASK
  22.             b = (carry << 1) & MASK
  23.  
  24.         # convert back to signed integer
  25.         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
  26.  
Advertisement
Add Comment
Please, Sign In to add comment