Leetcode-Sum of Two Integers
2016-08-27 18:15
417 查看
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.
解题思路:两个数的异或值可以得到两个数不进位的加法,如1 xor 2 = 0001 xor 0010 = 0011
两个数相与可以得到两个数相加进位,如 0001 & 0010 = 0000
所以只需要将两数相与取进位值,异或取非进位值,并对进位值移位后与非进位值相加,则可以得到两数相加的结果。
+and
-.
Example:
Given a = 1 and b = 2, return 3.
解题思路:两个数的异或值可以得到两个数不进位的加法,如1 xor 2 = 0001 xor 0010 = 0011
两个数相与可以得到两个数相加进位,如 0001 & 0010 = 0000
所以只需要将两数相与取进位值,异或取非进位值,并对进位值移位后与非进位值相加,则可以得到两数相加的结果。
public static int Add(int s1, int s2) { while(true) { if(s2==0) break; else { int carry=s1&s2; s1=s1 ^ s2; s2=carry<<1; } } return s1; }
相关文章推荐
- 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] Sum of Two Integers
- [LeetCode]Sum of Two Integers
- leetcode371-----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:bits:Sum of Two Integers(371)