371. Sum of Two Integers
来源:互联网 发布:防晒霜推荐知乎 编辑:程序博客网 时间:2024/05/21 17:25
题目1
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.
Credits:
Special thanks to @fujiaozhu for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
解题思路
把二进制上的加法用位运算来替代.
第一步不考虑进位,对每一位相加。0加0与1加1的结果都0,0加1与1加0的结果都是1。这和异或的运算结果是一致。
第二步进位,对0加0、0加1、1加0而言,都不会产生进位,只有1加1时,会向前产生一个进位。此时我们可以想象成是两个数先做位与运算,然后再向左移动一位。只有两个数都是1的时候,位与得到的结果是1,其余都是0。
第三步把前两个步骤的结果相加
代码如下
class Solution {public: int getSum(int a, int b) { if (0 == b) return a; int sum = a ^ b; int add = (a & b) << 1; return getSum(sum, add); }};
- https://leetcode.com/problems/sum-of-two-integers/ ↩
0 0
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- 371. Sum of Two Integers
- Java学习笔记(基本数据类型和变量命名规则)
- 【编程马拉松】【025-数字三角形 】
- Application windows are expected to have a root view controller at the end of application launch'
- VMware12 安装MAC-OS-X 10.11
- 【编程马拉松】【026-是男人就下100层】
- 371. Sum of Two Integers
- Go语言学习笔记9
- Java中set集合
- 怎么充分利用大数据寻找商机?
- 自学PHP系列之一:xHtml技术
- Java中几个常用设计模式
- 好的收款接口及相应的说明文档
- Spring系列之J2EE开发的春天
- JAVA源码分析之---Object类(二)---hashCode,equals,clone方法的使用