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;
    }
};

 

 

转载于:https://www.cnblogs.com/goblinengineer/p/5197911.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值