Leetcode--Add to List 371. Sum of Two Integers
2017-08-02 10:34
405 查看
题目
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.
不使用+ - 实现加法
思路
位运算来实现代码
递归版本class Solution { public: int getSum(int a, int b) { if(b == 0) return a; return getSum(a^b, (a&b)<<1); } };
非递归版
class Solution { public: int getSum(int a, int b) { while(b) { int carry = a & b; a = a ^ b; b = carry << 1; } return a; } };
相关文章推荐
- Add to List 371. Sum of Two Integers
- leetcode 21. Merge Two Sorted Lists Add to List
- [Leetcode] 2.Add Two Numbers(List To Long,模拟)
- [LeetCode]371. Sum of Two Integers【&2. Add Two Numbers】
- LeetCode-371. Sum of Two Integers (Java)
- leetcode_ Add to List 108. Convert Sorted Array to Binary Search Tree
- leetcode_ Add to List 121. Best Time to Buy and Sell Stock
- LeetCode-371. Sum of Two Integers
- LeetCode- Add to List 88. Merge Sorted Array
- Leetcode--Add to List 374. Guess Number Higher or Lower
- [LeetCode]371. Sum of Two Integers
- LeetCode: 371. Sum of Two Integers
- LeetCode--371. Sum of Two Integers
- Leetcode 371. Sum of Two Integers
- 【LeetCode】417. Pacific Atlantic Water Flow Add to List
- LeetCode 2.Add Two Numbers,67.Add Binary,371.Sum of Two Integers,66.Plus One
- LeetCode-371. Sum of Two Integers-Java
- [leetcode][list] Add Two Numbers
- [leetcode] 371. Sum of Two Integers 解题报告
- Leetcode--Add to List 215. Kth Largest Element in an Array