leetcode371: Sum of 2 Integers
2016-07-04 17:24
239 查看
题目描述:
Calculate the sum of two integers a and b, but you are not allowed to use the operator
Example:
Given a = 1 and b = 2, return 3.
网上流传最广的方法:
原理:使用异或操作可以进行二进制不带进位的加减,与操作可以得到进位。
即:
result0 = a ^ b
carry0 = (a & b) << 1
于是有:a + b = result0 + carry0
再进行一次迭代:
result1 = result0 ^ carry0
carry1 = (result0 & carry0) << 1
以此类推:有a + b = result0 + carry0 = result1
+ carry1 = result2 + carry2 = ······ = resultN +
carryN = result(N+1) ,直到carry(N+1)=0得到结果。
所以步骤是:
1、先让两个数字相加,但是不进位,即做异或的操作;
2、计算产生的进位,让两个数字位与操作,然后向左移动一位;
3、前两步的结果相加,重复前两个步骤直到进位为0;
很容易写出代码:
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.
网上流传最广的方法:
原理:使用异或操作可以进行二进制不带进位的加减,与操作可以得到进位。
即:
result0 = a ^ b
carry0 = (a & b) << 1
于是有:a + b = result0 + carry0
再进行一次迭代:
result1 = result0 ^ carry0
carry1 = (result0 & carry0) << 1
以此类推:有a + b = result0 + carry0 = result1
+ carry1 = result2 + carry2 = ······ = resultN +
carryN = result(N+1) ,直到carry(N+1)=0得到结果。
所以步骤是:
1、先让两个数字相加,但是不进位,即做异或的操作;
2、计算产生的进位,让两个数字位与操作,然后向左移动一位;
3、前两步的结果相加,重复前两个步骤直到进位为0;
很容易写出代码:
public class SumOf2Int { static int getSum(int a, int b) { int x, y; while (b != 0){ x = a ^ b; y = (a & b) << 1; a = x; b = y; } return a; } public static void main(String[] args) { System.out.println(getSum(-15, -5)); } }
相关文章推荐
- 《HTTP权威指南》——客户端识别与cookie机制
- RecyclerView
- vmware + ubuntu 16.04
- IO - 同步,异步,阻塞,非阻塞
- 117. Populating Next Right Pointers in Each Node II
- MySQL对于datetime 源码分析
- mvvm 密码框 绑定 简便方法
- SQL 行转列
- spark机器学习笔记:(六)用Spark Python构建回归模型
- 【FAQ】ubuntu:java opensdk 7 如何升级到 8?
- XML基本语法
- Linkedin 数据爬虫笔记
- ios 警告消除 directory not found for option
- cocos2d-x-3.4 无法打开包含文件extensions/ExtensionExport.h
- 2.安卓源码下载
- 用java代码调用名片识别接口示例代码
- mark php安全问题
- Ubuntu双系统
- find 删除拷贝用法
- 软件工程个人日报 2016/7/4