LintCode: A + B Problem

A + B Problem

Similar Problems:

Write a function that add two numbers A and B. You should not use + or any arithmetic operators.

There is no need to read data from standard input stream. Both parameters are given in function aplusb, you job is to calculate the sum and return it.

Are a and b both 32-bit integers?

Can I use bit operation?

Sure you can.
Given a=1 and b=2 return 3


Credits To:

Leave me comments, if you have better ways to solve.

## Blog link:
class Solution:
    @param a: An integer
    @param b: An integer
    @return: The sum of a and b
    def aplusb(self, a, b):
        ## Basic Ideas:
        ##   a ^ b: add without carry
        ##   (a & b) << 1: carry
        ##  Assumption: the result won't overflow
        ## Complexity: Time O(1), Space O(1)
        mod = 0xFFFFFFFF
        while b != 0:
            a, b = (a ^ b) & mod, ((a & b) << 1) & mod
        return a

Share It, If You Like It.

Leave a Reply

Your email address will not be published.