LeetCode - 371. Sum of Two Integers
来源:互联网 发布:大庆石化公司网络培训 编辑:程序博客网 时间:2024/04/25 18:47
在不准使用+和-的情况下实现两个整数的加法,那么肯定要用到位运算了。我们考虑位运算加法的四种情况:
0 + 0 = 0
1 + 0 = 1
0 + 1 = 0
1 + 1 = 1(with carry)
在学习位运算的时候,我们知道XOR的一个重要特性是不进位加法,那么只要再找到进位,将其和XOR的结果加起来,就是最后的答案。通过观察上面的四种情况我们可以发现,只有在两个加数的值都是1的时候才会产生进位,所以我们采用&来计算进位的情况,但是注意到由于是进位,所以我们必须要将&的结果左移一位,然后再和XOR的结果相加。怎么相加呢,还是要调用getSum这个函数,这里需要再添加上递归最底层的情况,b == 0,也就是进位是0,这时候只要返回a就可以了,代码如下:
public class Solution { public int getSum(int a, int b) { if(b == 0) return a; // when carry is zero, return int sum = a ^ b; // calculate sum without carry int carry = (a & b) << 1; // calculate carry return getSum(sum, carry); }}
知识点:
1. 使用位运算实现的加法,这是个基础的问题,记录一下
2. XOR的性质,不进位加法
0 0
- LeetCode 371. Sum of Two Integers
- 371. Sum of Two Integers LeetCode OJ
- [Leetcode]371. Sum of Two Integers
- LeetCode - 371. Sum of Two Integers
- <LeetCode OJ> 371. Sum of Two Integers
- LeetCode 371. Sum of Two Integers
- leetcode 371. Sum of Two Integers
- leetcode 371.Sum of Two Integers
- LeetCode 371. Sum of Two Integers
- 371. Sum of Two Integers(Leetcode)
- leetcode 371. Sum of Two Integers
- 【leetcode】371. Sum of Two Integers【E】
- [leetcode] 371. Sum of Two Integers
- leetcode.371. Sum of Two Integers
- 371. Sum of Two Integers--LeetCode Record
- LeetCode—371. Sum of Two Integers
- Leetcode 371. Sum of Two Integers
- LeetCode 371. Sum of Two Integers
- Java-密码加密
- 图片磁盘缓存量的大小显示和,清除缓存实现 ------ 基于glide
- C# 连接SQL数据库类
- 异步请求
- 嵌入式学习-uboot-lesson9.1-C语言环境初始化
- LeetCode - 371. Sum of Two Integers
- 学习计划2
- 【水水水】678A - Johny Likes Numbers
- POJ - 3281 Dining 网络流
- hdu 4513(manacher+dp)
- Android 简单登录界面
- gdb调试Clang2.6 (clang-cc)
- Annotation
- HttpURLConnection简介