[Lintcode学习笔记](1. A + B Problem)

题目 “A + B Problem

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

Challenge:
Of course you can just return a + b to get accepted. But Can you challenge not do it like that?(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.

Notice:
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.

话不多说,直接上代码

// 直接从lintcode上拷贝的代码
class Solution {
public:
    /**
     * @param a: An integer
     * @param b: An integer
     * @return: The sum of a and b 
     */
    int aplusb(int a, int b) {
        // write your code here
        int a_=0,b_=0;
        while(b!=0)
        {
            a_=a^b;
            b_=(a&b)<<1;
            a=a_;
            b=b_;
        }
        return a;
    }
};

代码解读

  1. 创建两个中间变量a_,b_
  2. 将待做加法运算的a,b进行按位异或,结果存入a_
  3. 将a,b按位与,并左移一位,结果存入b_
  4. a=a_
  5. b=b_
  6. 直到b的值等于0

这是我第一次写博客,过程有点简单,写的不好的地方,还请各位勿喷。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值