leetcode[Sum of Two Integers]
2017-07-14 00:14
429 查看
解法一(递归):
public class Solution {
//计算两个数的和,又不让用+和-运算符
//根据加法的原理:相加,进位 从而进行处理
//因为不允许用+、-,所以根据位运算来表示相加和进位
public int getSum(int a, int b) {
if(b == 0){//递归出口,永远都不可能有进位
return a;
}
//根据位运算的总结,a^b可用来求每一位相加后剩下的结果
int temp = a ^ b;
//根据位运算的总结,(a&b)<<1可用来求每一位是否有进位
int carry = (a & b) << 1;//进位嘛,左移一位
return getSum(temp, carry);//将每一位相加后的结果加上进位,就是最终结果
}
}
解法二(非递归):
public class Solution {
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;
}
}
public class Solution {
//计算两个数的和,又不让用+和-运算符
//根据加法的原理:相加,进位 从而进行处理
//因为不允许用+、-,所以根据位运算来表示相加和进位
public int getSum(int a, int b) {
if(b == 0){//递归出口,永远都不可能有进位
return a;
}
//根据位运算的总结,a^b可用来求每一位相加后剩下的结果
int temp = a ^ b;
//根据位运算的总结,(a&b)<<1可用来求每一位是否有进位
int carry = (a & b) << 1;//进位嘛,左移一位
return getSum(temp, carry);//将每一位相加后的结果加上进位,就是最终结果
}
}
解法二(非递归):
public class Solution {
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;
}
}
相关文章推荐
- LeetCode 371: Sum of Two Integers 题解
- [leetcode-371]Sum of Two Integers(java)
- LeetCode:Sum of Two Integers
- 【leetcode74】Sum of Two Integers(不用+,-求两数之和)
- leetcode NO.371 sum of two integers
- [LeetCode] Sum of Two Integers 两数之和
- LeetCode:Sum of Two Integers
- leetcode:bits:Sum of Two Integers(371)
- [LeetCode]Sum of Two Integers
- [LeetCode] Sum of Two Integers
- LeetCode 371 Sum of Two Integers
- 【leetcode74】Sum of Two Integers(不用+,-求两数之和)
- Leetcode-Sum of Two Integers
- leetcode 371 Sum of Two Integers java实现
- 【leetcode74】Sum of Two Integers(不用+,-求两数之和)
- #leetcode#Sum of Two Integers
- LeetCode 第 371 题 (Sum of Two Integers)
- leetcode Sum of Two Integers
- LeetCode[371] Sum of Two Integers
- leetcode--sum of two integers