LintCode-A+B Problem

For given numbers a and b in function aplusb, return the sum of them.

Note

You don't need to parse the input and output. Just calculate and return.

Example

If a=1 and b=2 return 3

Challenge

Can you do it with out + operation?

Clarification

Are a and b both 32-bit integers?

    - Yes.

Analysis:

Use bit manipulation.

Solution 1:

Caluclate every bit.

 1 class Solution {
 2     /*
 3      * param a: The first integer
 4      * param b: The second integer
 5      * return: The sum of a and b
 6      */
 7     public int aplusb(int a, int b) {
 8         int res = 0;
 9         int carry = 0;
10         for (int i=0;i<32;i++){
11             int a1 = a & 1;
12             int b1 = b & 1;
13             int val = 0;
14             if (a1==1 && b1==1 && carry==1){
15                 val = 1;
16                 carry = 1;
17             } else if ( (a1==1 && b1==1) || (a1==1 && carry==1) || (b1==1 && carry==1) ) {
18                 val = 0;
19                 carry = 1;
20             } else if (a1==1 || b1==1 || carry==1) {
21                 val = 1;
22                 carry = 0;
23             } else {
24                 val = 0;
25                 carry = 0;
26             }
27             val = val << i;
28             res = res | val;
29             a = a >> 1;
30             b = b >> 1;
31         }
32 
33         return res;
34         
35     }
36 };

Solution 2:

For a + b in any base, we can treat the plus as two part: 1. a + b without carry; 2. the carry generated by a +b. The a+b then equals to part 1 plus part 2. If part1+part2 generates more carry, we can then repeat this procedure, until there is no carry.

 1 class Solution {
 2     /*
 3      * param a: The first integer
 4      * param b: The second integer
 5      * return: The sum of a and b
 6      */
 7     public int aplusb(int a, int b) {
 8         while (b!=0){
 9             int carry = a & b; //their carry (actuall, need to move to right by one bit.
10             a = a^b;           //their plus result without carry.
11             b = carry << 1;
12         }
13         return a;
14     }
15 };

 

 

转载于:https://www.cnblogs.com/lishiblog/p/4194937.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值