LeetCode 371. Sum of Two Integers
来源:互联网 发布:winpe装linux 编辑:程序博客网 时间:2024/06/16 12:46
371. Sum of Two Integers
Description
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.
Solution
- 题目的意思是不使用加法运算符和减法运算符来完成两个数的加法。
- 我们可以使用位运算模拟机器对加法的处理(加法器组成的ALU),我们可以通过异或得到各位相加,与运算获得各位是否需要进位。
- 我们分析原始的竖式加法,各位相加,如果大于进制数就进位,位运算是基于二进制的,所以>=2就需要进位。
a ^ b
获得的是两个数按位相加的结果(未进行进位,比如2 ^ 3 就是 10 ^ 11 得到 01 此时需要进位)a & b
获得的是两个数各位相加需要进位的位(比如2 & 3就是10 & 11 就是 10 代表第二位需要进位,) 但是我们进位是需要向前面一位进位,所以(a & b) << 1
得到需要进到的那一位。 代码如下:
class Solution {public: int getSum(int a, int b) { return b == 0?a:getSum(a ^ b,(a & b) << 1); }};
阅读全文
0 0
- LeetCode 371. Sum of Two Integers
- 371. Sum of Two Integers LeetCode OJ
- [Leetcode]371. Sum of Two Integers
- LeetCode - 371. Sum of Two Integers
- <LeetCode OJ> 371. Sum of 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
- 371. Sum of Two Integers(Leetcode)
- leetcode 371. Sum of Two Integers
- 【leetcode】371. Sum of Two Integers【E】
- [leetcode] 371. Sum of 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 371. Sum of Two Integers
- redis集群命令
- hadoop2.x入门:编写mapreduce对气象数据集求每日最高气温和最低气温
- Android—(通知、闹钟)
- 音译 —— 本身的含义
- MongoDB学习
- LeetCode 371. Sum of Two Integers
- Return of the Nim
- JS交互
- 【每日算法】堆排序
- MapReduce学习(3)
- 通讯录 c++数组版
- 基于MATLAB的模拟退火算法求解TSP问题
- raft一致性算法
- 拓扑排序-Kahn算法