【Leetcode】371. Sum of Two Integers
2016-07-12 21:13
267 查看
1 解题思想
这道题本身来说很简单,就是实现加法,但是不允许用内置的加减来实现,那么这个就应该怎么实现呢?和题目一样,我用的是一个位运算,分为两个步骤:
1、输入 a,b
2、按照位把ab相加,不考虑进位,结果是 a xor b,即1+1 =0 0+0 = 0 1+0=1,进位的请看下面
3、计算ab的进位的话,只有二者同为1才进位,因此进位可以标示为 (a and b) << 1 ,注意因为是进位,所以需要向左移动1位
4、于是a+b可以看成 (a xor b)+ ((a and b) << 1),这时候如果 (a and b) << 1 不为0,就递归调用这个方式吧,因为(a xor b)+ ((a and b) << 1) 也有可能进位,所以我们需要不断的处理进位。
2 原题
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.
3 AC解
public class Solution {public int getSum(int a, int b) {
int result = a ^ b; // 按位加
int carray = (a & b) << 1; // 计算进位
if(carray!=0) return getSum(result,carray); //判断进位与处理
return result;
}
}
易错点:<< 运算的优先级高。注意要加括号。 http://blog.csdn.net/mebiuw/article/details/51788817
相关文章推荐
- Android简易实战教程--第七话《在内存中存储用户名和密码》
- Android简易实战教程--第七话《在内存中存储用户名和密码》
- 如何通过linux ssh远程linux不用输入密码登入
- java动态代理框架
- 使用System.Drawing.Imaging.dll进行图片的合并
- <Spark>制作Spark-On-Yarn镜像
- HTTP的会话有四个过程,请选出不是的一个()----百度2016研发工程师笔试题(六)
- 台湾清华大学彭明辉教授的研究生手册(如何阅读论文)
- (Eclipse) 安装Subversion1.82(SVN)插件
- windows的DOS窗口如何修改大小
- 创建一个会滚动的textView
- 【Frame Animation 逐帧动画】
- 使用Junit进行单元测试代码
- CreateProcessWithToken 1058 error
- ubuntu opencv 环境配置 +Qt pro 文件
- 免费制作gif图片工具
- objc与鸭子对象(上)
- ssh框架学习-struts2 使用自定义拦截器进行文字过滤拦截
- Android 中 Fragment 的简单使用
- Day 6 点亮属于你的LED灯