From f8c808b25f57ee993dade378bd1fa44b54b26e4d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=94=90=E6=A0=91=E6=A3=AE?= <14021051@buaa.edu.cn> Date: Fri, 26 Oct 2018 23:40:21 +0800 Subject: [PATCH] Create 371. Sum of Two Integers.md --- 371. Sum of Two Integers.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 371. Sum of Two Integers.md diff --git a/371. Sum of Two Integers.md b/371. Sum of Two Integers.md new file mode 100644 index 0000000..2263463 --- /dev/null +++ b/371. Sum of Two Integers.md @@ -0,0 +1,31 @@ +# [371. Sum of Two Integers](https://leetcode.com/problems/sum-of-two-integers/description/) +# 思路 +求两个数的和,要求不能使用操作符+、-。 +我们知道计算机底层中的四则运算都是用门电路通过简单的逻辑操作实现的, 例如对于一位的二进制加法: + +| a | b | sum(和) | cin(进位) | +| :-: | :-: | :-: | :-: | +| 0 | 0 | 0 | 0 | +| 0 | 1 | 1 | 0 | +| 1 | 0 | 1 | 0 | +| 1 | 1 | 0 | 1 | + +所以一位加法规则是: `sum = a ^ b, cin = a & b`. +对于多位的加法,我们可以先分别求出sum和cin, 再用sum和左移一位的cin相加求出新的sum和cin, 循环直到cin为0. + +# C++ +``` C++ +class Solution { +public: + int getSum(int a, int b) { + int res = a ^ b, cin = a & b; // 异或操作'^': 相同为0不同为1 + while(cin != 0){ + a = cin << 1; + b = res; + res = a ^ b; + cin = a & b; + } + return res; + } +}; +```