Files
leetcode/key/2235.md
2025-09-15 21:12:04 +08:00

33 lines
2.0 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 两整数相加
[具体算法](../23/08/Q2235.cpp)
## 位运算
- 不使用加法运算符
假设 num1<sub>i</sub> 和 num2<sub>i</sub>分别表示`num1``num2` 的第 iii 个二进制位。一共有 4 种情况:
| num1<sub>i</sub> | num2<sub>i</sub> | 不进位的和⊕ | 进位(&) |
| :--------------: | :--------------: | :---------: | ------- |
| 0 | 0 | 0 | 0 |
| 0 | 1 | 1 | 0 |
| 1 | 0 | 1 | 0 |
| 1 | 1 | 0 | 1 |
观察可以发现,“不进位的和”与“异或运算”有相同规律,而进位则与“与”运算规律相同,并且需要左移一位。
因此:
- 对两数进行按位与运算 &&,然后左移一位,得到进位,记为 carry
- 对两数进行按位异或运算 ⊕,得到不进位的和;
- 问题转换为求:“不进位的数 + 进位” 之和;
- 循环,直至第二个数为 0返回第一个数即可也可以用递归实现
## 对于 C++
- 将先算出两数中二进制需要进位的点,然后二进制左移一位,相当于算出了所有需要进位的位,并且把这个位转换为了其下一位的值,后面只需要把结果和这个值相加即可。
- 然后将两树中二进制不需要进位的点相加,也就是 01 和 10 两种使用异或操作就可加为1并保存到num1中方便下一次运算。
- 此时num2就没用了他的所有位都被计算过了此时就可以把num2换成计算进位的时候所保存的值
- 再进入下一轮运算时现在的num1相当于是上一轮运算时num1加上了num2的所有无需进位的值num2相当于是两数相加时所有需要进位的值变成了进位后的值然后这一轮在相加重复步骤即可。
- 由于num2在每一轮最后的值都是与操作再进一相当于进位值最后总有无须进位的时候此时num2会变为0因此循环出口就是num2变为0的时候