XIAOQING打卡第一天

nceko 2021-12-10 19:44:27

## 题目一:加法
链接:[两整数之和](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;                    
    }

};
```
 

...全文
77 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
小笼包95 2021-12-10
  • 打赏
  • 举报
回复

64,199

社区成员

发帖
与我相关
我的任务
社区描述
学习「 算法 」的捷径就是 「 题海战略 」,社区由「 夜深人静写算法 」作者创建,三年ACM经验,校集训队队长,亚洲区域赛金牌,世界总决赛选手。社区提供系统的训练,答疑解惑,面试经验,大厂内推等机会
社区管理员
  • 英雄哪里出来
  • 芝麻粒儿
  • Amy卜bo皮
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

QQ群:480072171

英雄算法交流 8 群

 

试试用AI创作助手写篇文章吧