[LeetCode] Sum of Two Integers(用位运算实现加法)
2017-02-17 11:32
253 查看
题目链接在此
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.
要求代码里不能出现 + 和 - 符号,只能用位运算咯。
这位大神把加法、减法、循环/递归 的做法的列出来了:
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.
要求代码里不能出现 + 和 - 符号,只能用位运算咯。
这位大神把加法、减法、循环/递归 的做法的列出来了:
// Iterative int getSum(int a, int b) { if (a == 0) return b; if (b == 0) return a; while (b != 0) { int carry = a & b; a = a ^ b; b = carry << 1; } return a; } // Iterative int getSubtract(int a, int b) { while (b != 0) { int borrow = (~a) & b; a = a ^ b; b = borrow << 1; } return a; } // Recursive int getSum(int a, int b) { return (b == 0) ? a : getSum(a ^ b, (a & b) << 1); } // Recursive int getSubtract(int a, int b) { return (b == 0) ? a : getSubtract(a ^ b, (~a & b) << 1); } // Get negative number int negate(int x) { return ~x + 1; }
相关文章推荐
- [leetcode] 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 371 Sum of Two Integers java实现
- LeetCode 371: Sum of Two Integers 题解
- #leetcode#Sum of Two Integers
- 【Leetcode】Sum of Two Integers
- 【leetcode74】Sum of Two Integers(不用+,-求两数之和)
- 【leetcode74】Sum of Two Integers(不用+,-求两数之和)
- LeetCode---Sum of Two Integers
- leetcode NO.371 sum of two integers
- [Leetcode #371]Sum of Two Integers 不使用加法运算符完成加法运算
- LeetCode[371] Sum of Two Integers
- LeetCode 371 : Sum of Two Integers(Java)
- [LeetCode]Sum of Two Integers
- LeetCode 第 371 题 (Sum of Two Integers)
- leetcode Sum of Two Integers
- LeetCode "Sum of Two Integers"