A+B problem

leetcode 开始收费了,开始转战lintcode。

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

Clarification

Are a and b both 32-bit integers?

Yes.

Can I use bit operation?

Sure you can.

Example

Given a=1 and b=2 return 3

让你计算两数之和,条件是不准用+运算符,首先想到是a+b = (a^2-b^2)/(a-b). 这样做完全符合条件,但是不是题目本身想考察的,bit operation提示我们可能要用到位运算,谷歌了一下,a+b可以通过位运算描述为:

    a = a^b --------> a,b异或,表示不带进位的相加. (1)
    b = (a&b)<<1 ------> a,b相与后左移,表示进位 (2)

重复上面的步骤,直到b为0, 此时a的值即为所求. 不过这种方法的runtime更·长一些.
两种方式的代码:

    int aplusb(int a, int b) {
        // write your code here
        int temp;
        while(b != 0){

        temp = a&b;
        a = a^b;
        b = temp<<1;
    }

    return a;
}

int aplusb(int a, int b) {
    // write your code here
    if(a == b)
        return 2*b;
    int temp = a*a-b*b;

    return temp/(a-b);
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值