LeetCode 371.Sum of Two Integers
来源:互联网 发布:无尽的传说2 mac 破解 编辑:程序博客网 时间:2024/06/03 03:59
Description:
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.
思路
不使用算术运算求和那么只能考虑直接在二进制位上进行位运算,事实上利用异或运算(^)和与运算(&)就能完成加法运算要做的事情.
异或运算完成相加但是不进位,而与运算计算出哪些地方需要进位,在通过左移运算(<<)就可以完成进位操作了。
1.循环的方法
class Solution {public: int getSum(int a, int b) { int sum = a; while (b != 0) { sum = a ^ b;//calculate sum of a and b without thinking the carry b = (a & b) << 1; //calculate the carry a = sum; //add sum(without carry) and carry } return sum; }};
2.递归的方法
class Solution {public: int getSum(int a, int b) { if(a && b) return getSum(a^b, (a&b) << 1); else return a|b; }};
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
- sublime配置等
- springmvc基础知识
- GDB寄存器和内存
- C++的高级特性
- 用charles拦截android设备https,证书无效的解决方法
- LeetCode 371.Sum of Two Integers
- Julia :迎接0.6的到来
- Java中按值传递问题
- 数据结构-二叉树(包含递归和非递归版本)
- Java中hashCode的作用
- python交互模式下退格键乱码问题
- Fn+W
- 学习GIT
- IOS开发学习笔记(四)