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代码
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; }
相关文章推荐
- Leetcode 371. Sum of Two Integers JAVA语言
- LeetCode-371. Sum of Two Integers (Java)
- leetcode解题之371. Sum of Two Integers Java版 (不使用加减乘除做加法)
- Java [leetcode 29]Divide Two Integers
- Leetcode 371. Sum of Two Integers 位运算实现加法 解题报告
- 371. Sum of Two Integers--LeetCode Record
- 【Leetcode】371. Sum of Two Integers
- 【一天一道LeetCode】#371. Sum of Two Integers
- 【LeetCode-面试算法经典-Java实现】【029-Divide Two Integers(两个整数相除)】
- LeetCode 371. Sum of Two Integers
- LeetCode—371. Sum of Two Integers
- leetcode 371. Sum of Two Integers
- leetcode 371 Sum of Two Integers java实现
- [leetcode] 371. Sum of Two Integers 解题报告
- Leetcode 371. Sum of Two Integers
- Java for LeetCode 029 Divide Two Integers
- (Java)LeetCode-29. Divide Two Integers
- [leetcode-371]Sum of Two Integers(java)
- <LeetCode OJ> 371. Sum of Two Integers
- 【一天一道LeetCode】#371. Sum of Two Integers