您的位置:首页 > 其它

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 
+
 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: