码迷,mamicode.com
首页 > 其他好文 > 详细

Sum of Two Integers

时间:2017-09-06 10:08:58      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:log   col   四则运算   ret   blog   cal   not   gets   加法   

Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.

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

 

分析:不通过四则运算符号完成求和;

思路:很明显只能通过二进制的位运算来完成。这里查看一篇博客。

https://ych0112xzz.github.io/2016/10/27/OperationwithBits/

简述加法的原理:

二进制数求和的过程可以分解为对应位数直接相加再加上相对应的进位。

1,直接相加用异或可以完成: 

  0101+0101=0000

  0101^0101=0000

2,进位可以用(a&b)<<1完成:

  0101+0101=1010

  (0101&0101)<<1=1010

第一和第二部的结果相加只需要重复一次步骤1即可。对于多次进位,把条件设置为当步骤二结果为0是结束。

JAVA CODE

class Solution {
    public int getSum(int a, int b) {
        return b == 0 ? a : getSum(a ^ b, (a & b) << 1);
    }
}

 

Sum of Two Integers

标签:log   col   四则运算   ret   blog   cal   not   gets   加法   

原文地址:http://www.cnblogs.com/baichangfu/p/7482762.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!