lintcode-easy-A+B problem

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

Example

Given a=1 and b=2 return 3

Note

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.

Challenge

Of course you can just return a + b to get accepted. But Can you challenge not do it like that?

Clarification

Are a and b both 32-bit integers?

  • Yes.

Can I use bit operation?

  • Sure you can.

 

这道题相当于用编程语言写一个32位加法器,记不住可以搜一下

加法器原理:

sum = a^b^carry

carry = (a^b) | carry&(a^b)

 

逐个bit操作,把每一位的结果加到变量中去

这道题没有要求考虑溢出,不过面试可能有必要问一下,虽然我还没面过。

class Solution {
    /*
     * param a: The first integer
     * param b: The second integer
     * return: The sum of a and b
     */
    public int aplusb(int a, int b) {
        // write your code here, try to do it without arithmetic operators.
        
        int carry = 0;
        int sum = 0;
        for(int i = 0; i < 32; i++){
            sum = sum | (((a >> i) & 1) ^ ((b >> i) & 1) ^ carry) << i;
            carry = ((a >> i) & 1) & ((b >> i) & 1) | ((((a >> i) & 1) ^ ((b >> i) & 1)) & carry);
        }
        
        return sum;
    }
};

 

 

你可能感兴趣的:(lintcode-easy-A+B problem)