64,199
社区成员
发帖
与我相关
我的任务
分享## 题目一:加法
链接:[两整数之和](https://leetcode-cn.com/problems/sum-of-two-integers/)
**解题思路**:
例如 1 +2 =3 => (0001)B ^ (0010)B=(0011)B
But 1+3=4 => (0001)B ^ (0011)B=(0010)B=2 !=4不成立
So 由上可以看出'^'异或 是不会进位的加法,'&'按位与则 可以记录进位的位数。
**C++:**
```cpp
class Solution {
public:
int getSum(int a, int b) {
unsigned int x = a & b;
int s =a^b;
while(x!=0){
x<<=1;
int sum= s ^ x;
x= s & x;
s=sum;
}
return s;
}
};
```
**Python:**
```java
class Solution(object):
def getSum(self, a, b):
"""
:type a: int
:type b: int
:rtype: int
"""
return a+b
```
**JAVA:**
```python
class Solution {
public int getSum(int a, int b) {
return a+b;
}
}
```
## 题目二:乘法
链接:[递归乘法](https://leetcode-cn.com/problems/recursive-mulitply-lcci/submissions/)
**解题思路:**
此方法可以用递归和循环进行解答,循环一定要记得比较大小减少循环次数,不然超时。
```cpp
class Solution {
public:
int multiply(int A, int B) {
if(B==1)
return A;
else
return A+multiply(A,B-1);
}
};
```
**Python:**
```python
class Solution(object):
def multiply(self, A, B):
"""
:type A: int
:type B: int
:rtype: int
"""
if A>B:
x=B
sum=A
else:
x=A
sum=B
l=0
while x>0:
l+=sum
x=x-1
return l
```
## 题目三:除法
**链接**:[整数除法](https://leetcode-cn.com/problems/divide-two-integers/?from=from_parent_mindnote)
**解题思路:**
当我们
c++:
第一种方法:这种直接进行相除有一个缺点就是会发生溢出,当a=-2^31,b=-1时会返回2 ^31-1,而我们在32位的环境中的范围是[-2 ^31,2 ^31-1],所以下面if的情况需要特殊处理
第二种方法:就是通过位运算把除法变成减法。
```cpp
class Solution {
public:
int divide(int a, int b) {
if(a == -2147483648 && b == -1) {
return 2147483647;
}
return a / b;
}
};
```
赞