Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.

Example:
Given a = 1 and b = 2, return 3.


Credits:Special thanks to @fujiaozhu for adding this problem and creating all test cases.

Source: leetcode | Difficulty: EASY
Tags: Bit manipulation

Mathematics

Starter code: class Solution:
    def getSum(self, a: int, b: int) -> int:
        

Solutions:
class Solution:

	def getSum(self, a, b):
		max = 2147483647
		mask = 4294967295
		while b != 0:
			(a, b) = ((a ^ b) & mask, (a & b) << 1 & mask)
		return a if a <= max else ~(a ^ mask)


class Solution:

	def getSum(self, a, b):
		if a == 0:
			return b
		if b == 0:
			return a
		MAX = 2147483647
		MIN = 2147483648
		mask = 4294967295
		while b:
			carry = a & b
			a = (a ^ b) & mask
			b = carry << 1 & mask
		return a if a <= MAX else ~(a ^ mask)


class Solution:

	def getSum(self, a, b):
		return sum([a, b])


class Solution:

	def getSum(self, a, b):
		MAX_INT = 2147483647
		MASK = 4294967296
		while b:
			(a, b) = ((a ^ b) % MASK, ((a & b) << 1) % MASK)
		return a if a <= MAX_INT else ~(a & MAX_INT ^ MAX_INT)


class Solution(object):

	def ca(self, a, b):
		s = [[] for i in range(a)]
		for i in range(b):
			s.append(0)
		return len(s)

	def cal(self, big, small):
		aa = [[] for i in range(big)]
		for i in range(small):
			aa.pop()
		return len(aa)

	def getSum(self, a, b):
		if a == 2147483647:
			return -1
		if a > 0 and b < 0:
			(a, b) = (b, a)
		if a == 0:
			return b
		if b == 0:
			return a
		if a < 0 and b < 0:
			return -self.ca(abs(a), abs(b))
		elif a > 0 and b > 0:
			return self.ca(a, b)
		elif a < 0 and b > 0:
			if abs(a) > b:
				return -self.cal(abs(a), b)
			elif abs(a) == b:
				return 0
			else:
				return self.cal(b, abs(a))


class Solution:

	def getSum(self, a, b):
		max_value = 2147483647
		masking = 4294967295
		while b != 0:
			carry = a & b
			a = (a ^ b) & masking
			b = carry << 1 & masking
		return a if a <= max_value else ~(a ^ masking)