您的位置:首页 > 编程语言 > Java开发

LeetCode-371. Sum of Two Integers-Java

2016-10-28 01:52 459 查看
一. 题目

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时需要进1位(移位运算符<<),则进位操作位(数1 & 数2)<<1。

三. AC代码

public int getSum(int a, int b) {
int temp1=a^b;
int temp2=(a&b)<<1;
if(temp2!=0)
return getSum(temp1,temp2);
return temp1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: