Leetcode_371_Sum of Two Integers
来源:互联网 发布:retrofit json实体 编辑:程序博客网 时间:2024/06/05 16:10
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
思路:
(1)题意为给定两个整数,要求不用加减符号求它们的和。
(2)这题属于简单题,但是需要跳出思维的墙,需找解题方法。这里考虑将数字转为二进制后进行计算,分两种情况:相加时没有进位时直接相加;有进位时要注意加上进位。首先,不考虑进位,对每一位进行相加,这里使用^(按位异或,对应位相同为0,不同为1),即a^b。然后,判断并计算进位,对于0加0、0加1、1加0而言,都不会产生进位,只有1加1时才会向前产生一个进位。因此,进位可以看成是两个数先做位与(&)运算,然后再向左移动一位(相当于乘以2)。最后,将前两步结果相加。循环上面步骤,直至进位为0((a & b) << 1的结果为0)。
(3)代码实现如下所示。希望对你有所帮助。
package leetcode;public class Sum_of_Two_Integers { public int getSum(int a, int b) { while (b != 0) { int c = a ^ b; b = (a & b) << 1; a = c; } return a; }}
1 0
- Leetcode_371_Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- sum of two integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- Sum of Two Integers
- [IDE] 无图形Linux环境下的程序开发IDE: vicc 发布会 - 2
- 动态规划的关键 —— 子问题 & 公式化
- unity3d AI 学习--个体行为操控(1)
- STM32的存储器映射
- java中Final修饰符的使用
- Leetcode_371_Sum of Two Integers
- 数值的整数次方[剑指offer]之python实现
- Oracle优化器
- HDU ACM 11 2056 Rectangles
- findviewbyid和注解方式的自动生成工具
- codeforces 731FVideo Cards
- Angular之$resource服务
- 第一次用博客 只有一个要求:坚持写下去
- 关于汇编中有符号数和无符号数的判断