371. Sum of Two Integers
来源:互联网 发布:c语言 algin 编辑:程序博客网 时间:2024/06/15 20:20
原文地址:http://blog.csdn.net/u014203453/article/details/52495609
题目:Sum of Two Integers
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.
思路: 使用“与”与“异或”运算,其中按位“与”只是得到了进位信息,“异或”运算则是没有进位信息的“伪加法”。因此,要同时充分利用这两种运算求解加法运算。下面将11(二进制表示:1011)与5(二进制表示:0101)相加的运算过程如下:
(1)伪加运算结果(这里没有的进位信息的)
(2)计算进位(把进位计算进来)
可以看到上述与运算的进位信息应该是放在与运算为1的下一位,因此真正得到的进位结果为0010,也就是要对上述与运算结果进行左移一位。而此时,真正的加的结果应为Step1和Step2运算结果之和。
(3)迭代求解
重复以上两步,计算A+B直至进位信息B为0,得到加运算结果。
代码实现如下:
public static int getSum(int a, int b) { int carry = 0; while (b != 0) { // 伪加运算 a = a ^ b; // 计算进位信息 carry = a & b; // 左移得到真正的进位消息,进行下次重复迭代 b = carry << 1; } return a;}
1 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
- Tinyxml解析XML格式的文件
- HDU:Warcraft
- OkHttp的学习(二)
- 黑色幽默
- 快速幂算法基础
- 371. Sum of Two Integers
- 第四周项目3-随机函数应用于游戏(2)小学生算数能力测试系统
- 在硬件设备上运行应用
- 1065. A+B and C (64bit) (20)
- SCU2016-02 T题 (LIS)
- 第一行代码酷欧天气开发(二)
- BFS(广度优先搜索)基本介绍
- HDU:Find a way
- 盘点国内十大人工智能网站