Leetcode 371 求两个数的和
2018-08-03 14:31
103 查看
题意为不用+和-,求出a与b的和。
因此用位级运算。
我的思路是新建一个result遍历,将a和b按位求和,求和的方式是二进制加法专用符号:异或。
其中这句话carry=(tmpA&tmpB || tmpB&carry || tmpA&carry);的意思是:
如果tmpA、tmpB、carry中如果有两个以上为1,则进位置为1。
class Solution { public: int getSum(int a, int b) { int i=0; int result=0; int work=1; int carry=0; while(i<32){ int tmpA=work&a; int tmpB=work&b; int tmpSum=(tmpA^tmpB)^carry; result|=tmpSum; carry=(tmpA&tmpB || tmpB&carry || tmpA&carry); carry<<=(i+1); work<<=1; ++i; } return result; } };阅读更多
相关文章推荐
- leetcode371 位运算实现加法
- leetcode Two Sum II - Input array is sorted 两个数的和
- leetcode_167. Two Sum II - Input array is sorted 有序数组中找和为特定数的两个数的下标
- 通过位运算求两个数的和(求解leetcode:371. Sum of Two Integers)
- (leetcode)1. 查找数组中两个数之和为给定值Two Sum---Java
- leetcode 371 Sum of Two Integers C++
- leetcode371 Sum Of Integers 不用加法计算两个整数的和
- leetcode371题解
- LeetCode 1 找出两个数之和
- LeetCode 371 Sum of Two Intergers
- Leetcode 371(Java)
- 位操作-leetcode 371 Sum or Two Integers
- LeetCode219 查找相等两个数之间的最小距离
- LeetCode 371(Sum of Two Integers)
- leetcode之深搜递归回溯类-----1/167/653. two sum(记忆化搜索寻找和为给定值的两个数)
- leetcode 两个数相除,不用乘除和mode
- leetCode 第二题 两个数的和
- leetcode-java.T001_TwoSum 给定一个整数数组,找出其中两个数满足相加等于你指定的目标数字
- [LeetCode]1. 2Sum 数组中和为特定值的两个数
- leetcode 1 Two Sum(在无序数组中找两个数之和与目标值相等)