371. Sum of Two Integers
2016-11-04 17:58
176 查看
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.
思路:看來就用bit運算式
(a&b) << 1 可以表示進位
a^b 就是不進位的狀態
就一直loop 去計算
class Solution {
public:
int getSum(int a, int b) {
int add = 0;
int inc = 0;
do {
add = a^b;
inc = (a&b) << 1;
a = add;
b = inc;
} while(inc != 0);
return add;
}
};
b, but you are not allowed to use the operator + and
-.
Example:
Given a = 1 and b = 2, return 3.
思路:看來就用bit運算式
(a&b) << 1 可以表示進位
a^b 就是不進位的狀態
就一直loop 去計算
class Solution {
public:
int getSum(int a, int b) {
int add = 0;
int inc = 0;
do {
add = a^b;
inc = (a&b) << 1;
a = add;
b = inc;
} while(inc != 0);
return add;
}
};
相关文章推荐
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- LeetCode之371. Sum of Two Integers
- 371. Sum of Two Integers
- Leetcode 371. Sum of Two Integers JAVA语言
- 371. Sum of Two Integers
- leetcode解题之371. Sum of Two Integers Java版 (不使用加减乘除做加法)
- LeetCode - 371. Sum of Two Integers
- LeetCode 371. Sum of Two Integers
- 【leetcode】371. Sum of Two Integers【E】
- 371. Sum of Two Integers--LeetCode Record
- Leetcode 371. Sum of Two Integers
- 371. Sum of Two Integers
- leetcode 371. Sum of Two Integers(不用+ -实现加法)
- LeetCode Javascript实现 344. Reverse String 292. Nim Game 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers(位运算)
- 371. Sum of Two Integers
- LeetCode-371. Sum of Two Integers-Java
- 371. Sum of Two Integers